I am currently working with multiple geojson layers and overlaying them using groups in my project. To center the map on a specific geojson file, I referred to Mike's helpful answer available here -> Center a map in d3 given a geoJSON object
The issue I'm facing, which I suspect is due to JavaScript's asynchronous nature, is that when I define the projection on a large geojson file, other geojson features fail to project correctly.
How can I appropriately translate and scale the map within this system? Are there better approaches to tackle this problem?
EDIT
I've come up with a temporary solution, however, it restricts me from changing the projection programmatically. Using the debugger, I extracted values for s and t, then hard-coded those values at the beginning of the script after defining the projection, before calling any geojson functions.
Below is the snippet of my code:
var width = 1100,
height = 850;
var projection = d3.geo.mercator();
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var landGroup = svg.append("g"),
waterGroup = svg.append("g"),
urbanGroup = svg.append("g"),
borderGroup = svg.append("g");
d3.json("geoData/naLand.geojson", function(land) {
projection
.scale(1)
.translate([0,0]);
var b = path.bounds(land),
s = .95 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height),
t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2];
projection
.scale(s)
.translate(t);
landGroup.selectAll("path")
.data(land.features)
.enter()
.append("path")
.attr("d", path)
.attr("fill", "#888888")
.attr("stroke", "#111111")
})
d3.json("geoData/naWater.geojson", function(water) {
waterGroup.selectAll("path")
.data(water.features)
.enter()
.append("path")
.attr("d", path)
.attr("fill", "#C9DBFF")
.attr("stroke", "#0066FF")
})
d3.json("geoData/PNW_Municipalities.geojson", function(urban) {
urbanGroup.selectAll("path")
.data(urban.features)
.append("path")
.attr("d", path)
.attr("fill", "#666666")
.attr("stroke", "#666666")
})
d3.json("geoData/CanadianBorder.geojson", function(border) {
borderGroup.selectAll("path")
.data(border.features)
.enter()
.append("path")
.attr("d", path)
.attr("stroke", "#555555")
.attr("stroke-width", "3")
.attr("stroke-dasharray", "2,2")
.attr("fill", "transparent")
})