I need to display a D3 map with a topological / shaded relief background. All user functionalities need to be implemented (e.g. zoom and panning)
So far, I have layered the map over a PNG that has the topology. I then did some hacking around with the projection to align the PNG border with the map borders. I then allow the user to zoom the PNG (eg: http://bl.ocks.org/pbogden/7363519). The result is actually very good. When I pan and zoom the map moves with the PNG which is great (image below):
The problem is that the PNG is very heavy (20MB), and the whole resulting experience is seriously buggy to the point that is is unusable. Results are obviously use a lower resolution image, but then the topology looks crap when the user zooms in. I tried converting the PNG to JPG ... which was actually worse!
What would be the best solution to achieve my goal in D3? Initial thoughts are as follows:
(1) The d3.geo.tile plugin (http://bl.ocks.org/mbostock/4132797). The difficulty here is that I would need to create my own tiles from my PNG image. Is this a promising avenue? Would I be able to layer a D3 map on top of that? I cannot find an example with custom tiles.
(2) I've seen this successful implementation of OpenSeaDragon and D3 (http://bl.ocks.org/zloysmiertniy/0ab009ca832e7e0518e585bfa9a7ad59). The issue here is that I am not sure whether it'll be possible to implement the desired D3 functionalities (zoom, pan, transitions) such that the D3 map and the underlying image move simultaneously.
(3) Any other thoughts or ideas?
To turn an image into tiles you'll need to have a georeferenced image - or be able to georeference the image yourself. As I believe you are using a natural earth dataset to create this image, you could use the source tif file and work with this. I use tile mill generally for my tiles (with some python) and it is fairly straightforward. You would not be able to use your png as is for tiles.
However, creating at tile set is unnecessary if you are looking for a hillshade or some sort of elevation/terrain texture indication. Using a leaflet example here, you can find quite a few tile providers, the ESRI.WorldShadedRelieve looks likes it fits the bill. Here's a demo with it pulled into d3 with a topojson feature drawn ontop:
var pi = Math.PI,
tau = 2 * pi;
var width = 960;
height = 500;
// Initialize the projection to fit the world in a 1×1 square centered at the origin.
var projection = d3.geoMercator()
.scale(1 / tau)
.translate([0, 0]);
var path = d3.geoPath()
.projection(projection);
var tile = d3.tile()
.size([width, height]);
var zoom = d3.zoom()
.scaleExtent([1 << 11, 1 << 14])
.on("zoom", zoomed);
var svg = d3.select("svg")
.attr("width", width)
.attr("height", height);
var raster = svg.append("g");
var vector = svg.append("g");
// Compute the projected initial center.
var center = projection([-98.5, 39.5]);
d3.json("https://unpkg.com/world-atlas#1/world/110m.json",function(error,data) {
vector.append("path")
.datum(topojson.feature(data,data.objects.land))
.attr("stroke","black")
.attr("stroke-width",2)
.attr("fill","none")
.attr("d",path)
// Apply a zoom transform equivalent to projection.{scale,translate,center}.
svg
.call(zoom)
.call(zoom.transform, d3.zoomIdentity
.translate(width / 2, height / 2)
.scale(1 << 12)
.translate(-center[0], -center[1]));
})
function zoomed() {
var transform = d3.event.transform;
var tiles = tile
.scale(transform.k)
.translate([transform.x, transform.y])
();
projection
.scale(transform.k / tau)
.translate([transform.x, transform.y]);
var image = raster
.attr("transform", stringify(tiles.scale, tiles.translate))
.selectAll("image")
.data(tiles, function(d) {
return d;
});
image.exit().remove();
// enter:
var entered = image.enter().append("image");
// update:
image = entered.merge(image)
.attr('xlink:href', function(d) {
return 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile/' + d.z + '/' + d.y + '/' + d.x + '.png';
})
.attr('x', function(d) {
return d.x * 256;
})
.attr('y', function(d) {
return d.y * 256;
})
.attr("width", 256)
.attr("height", 256);
vector.selectAll("path")
.attr("transform", "translate(" + [transform.x, transform.y] + ")scale(" + transform.k + ")")
.style("stroke-width", 1 / transform.k);
}
function stringify(scale, translate) {
var k = scale / 256,
r = scale % 1 ? Number : Math.round;
return "translate(" + r(translate[0] * scale) + "," + r(translate[1] * scale) + ") scale(" + k + ")";
}
body { margin: 0; }
<svg></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://unpkg.com/d3-tile#0.0.4/build/d3-tile.js"></script>
<script src="https://unpkg.com/topojson-client#3"></script>
You could certainly use OpenSeadragon for this. You'd want to turn the image into tiles; you don't need a specialized server for it... there are a number of standalone scripts you can use:
http://openseadragon.github.io/examples/creating-zooming-images/
Once you have that, OpenSeadragon handles the zooming and panning for you.
To overlay SVG so that it matches the zooming and panning, use the SVG overlay plugin:
https://github.com/openseadragon/svg-overlay
It works great with SVG produced by D3.
One thing to be aware of is that OpenSeadragon does not have any geo-specific functionality, so you'll position the overlay in image pixels rather than latitude/longitude.
BTW, OpenSeadragon can also work with non-tiled images, so if you want to give it a test before tiling your image, that's no problem. You'll just want to tile your image before production so you're not sending 20mb to your users.
Related
I have a country map that I display with d3js. I can't succeed to to make it work with this projection :
var projection = d3.geoConicConformal()
.center([2.454071, 46.279229])
.scale(0.1)
.translate([width / 2, height / 2]);
path.projection(projection);
(even if others map worked)
So I'm trying to use geoIdentity to avoid position :
var projection = d3.geoIdentity().reflectY(true).fitExtent([[100, 100], [width-100, height-100]], geojson); //.fitSize([width,height],geojson)
var path = d3.geoPath(projection);
This kind of work but the problem is that my map is wider that it should be. (In gesojson.io the map seems to have the good ratio) :
So I would like to reduce the width (X axis) to change the ratio. I tried with fitExtend and fitSize but nothing work, is there a solution to do this ?
EDIT for Andrew :
Here is what I have at first with geoConicalConformal (with fitsize/fitextend or not) :
I found a trick that work pretty well. Just remember that this is only a "trick".
You have to add transform scaleX (< 1 if the shape is too wide) style properties for each of your path :
deps.selectAll("path")
.data(geojson.features)
.enter()
.append("path")
.attr('class', 'department')
.attr("d", path)
.attr('id', d => "d" + d.properties.dep)
.style('transform', 'scaleX(0.7)')
For me, 0.7 is perfect, you have to adjust this parameters on your project. Then, Adjust fitExtend to make the whole shape move to the right because the scaleX < 1 while make the shape move to the left. For example :
var projection = d3.geoIdentity().reflectY(true).fitExtent([[width * 0.3, height * 0.1], [width * 1.3, height * 0.9]], geojson);
Currently in d3 if you have a geoJSON object that you are going to draw you have to scale it and translate it in order to get it to the size that one wants and translate it in order to center it. This is a very tedious task of trial and error, and I was wondering if anyone knew a better way to obtain these values?
So for instance if I have this code
var path, vis, xy;
xy = d3.geo.mercator().scale(8500).translate([0, -1200]);
path = d3.geo.path().projection(xy);
vis = d3.select("#vis").append("svg:svg").attr("width", 960).attr("height", 600);
d3.json("../../data/ireland2.geojson", function(json) {
return vis.append("svg:g")
.attr("class", "tracts")
.selectAll("path")
.data(json.features).enter()
.append("svg:path")
.attr("d", path)
.attr("fill", "#85C3C0")
.attr("stroke", "#222");
});
How the hell do I obtain .scale(8500) and .translate([0, -1200]) without going little by little?
My answer is close to Jan van der Laan’s, but you can simplify things slightly because you don’t need to compute the geographic centroid; you only need the bounding box. And, by using an unscaled, untranslated unit projection, you can simplify the math.
The important part of the code is this:
// Create a unit projection.
var projection = d3.geo.albers()
.scale(1)
.translate([0, 0]);
// Create a path generator.
var path = d3.geo.path()
.projection(projection);
// Compute the bounds of a feature of interest, then derive scale & translate.
var b = path.bounds(state),
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];
// Update the projection to use computed scale & translate.
projection
.scale(s)
.translate(t);
After comping the feature’s bounding box in the unit projection, you can compute the appropriate scale by comparing the aspect ratio of the bounding box (b[1][0] - b[0][0] and b[1][1] - b[0][1]) to the aspect ratio of the canvas (width and height). In this case, I’ve also scaled the bounding box to 95% of the canvas, rather than 100%, so there’s a little extra room on the edges for strokes and surrounding features or padding.
Then you can compute the translate using the center of the bounding box ((b[1][0] + b[0][0]) / 2 and (b[1][1] + b[0][1]) / 2) and the center of the canvas (width / 2 and height / 2). Note that since the bounding box is in the unit projection’s coordinates, it must be multiplied by the scale (s).
For example, bl.ocks.org/4707858:
There’s a related question where which is how to zoom to a specific feature in a collection without adjusting the projection, i.e., combining the projection with a geometric transform to zoom in and out. That uses the same principles as above, but the math is slightly different because the geometric transform (the SVG "transform" attribute) is combined with the geographic projection.
For example, bl.ocks.org/4699541:
The following seems to do approximately what you want. The scaling seems to be ok. When applying it to my map there is a small offset. This small offset is probably caused because I use the translate command to center the map, while I should probably use the center command.
Create a projection and d3.geo.path
Calculate the bounds of the current projection
Use these bounds to calculate the scale and translation
Recreate the projection
In code:
var width = 300;
var height = 400;
var vis = d3.select("#vis").append("svg")
.attr("width", width).attr("height", height)
d3.json("nld.json", function(json) {
// create a first guess for the projection
var center = d3.geo.centroid(json)
var scale = 150;
var offset = [width/2, height/2];
var projection = d3.geo.mercator().scale(scale).center(center)
.translate(offset);
// create the path
var path = d3.geo.path().projection(projection);
// using the path determine the bounds of the current map and use
// these to determine better values for the scale and translation
var bounds = path.bounds(json);
var hscale = scale*width / (bounds[1][0] - bounds[0][0]);
var vscale = scale*height / (bounds[1][1] - bounds[0][1]);
var scale = (hscale < vscale) ? hscale : vscale;
var offset = [width - (bounds[0][0] + bounds[1][0])/2,
height - (bounds[0][1] + bounds[1][1])/2];
// new projection
projection = d3.geo.mercator().center(center)
.scale(scale).translate(offset);
path = path.projection(projection);
// add a rectangle to see the bound of the svg
vis.append("rect").attr('width', width).attr('height', height)
.style('stroke', 'black').style('fill', 'none');
vis.selectAll("path").data(json.features).enter().append("path")
.attr("d", path)
.style("fill", "red")
.style("stroke-width", "1")
.style("stroke", "black")
});
With d3 v4 or v5 its getting way easier!
var projection = d3.geoMercator().fitSize([width, height], geojson);
var path = d3.geoPath().projection(projection);
and finally
g.selectAll('path')
.data(geojson.features)
.enter()
.append('path')
.attr('d', path)
.style("fill", "red")
.style("stroke-width", "1")
.style("stroke", "black");
Enjoy, Cheers
I'm new to d3 - will try to explain how I understand it but I'm not sure I got everything right.
The secret is knowing that some methods will operate on the cartographic space (latitude,longitude) and others on the cartesian space (x,y on the screen). The cartographic space (our planet) is (almost) spherical, the cartesian space (screen) is flat - in order to map one over the other you need an algorithm, which is called projection. This space is too short to deep into the fascinating subject of projections and how they distort geographic features in order to turn spherical into plane; some are designed to conserve angles, others conserve distances and so on - there is always a compromise (Mike Bostock has a huge collection of examples).
In d3, the projection object has a center property/setter, given in map units:
projection.center([location])
If center is specified, sets the projection’s center to the specified location, a two-element array of longitude and latitude in degrees and returns the projection. If center is not specified, returns the current center which defaults to ⟨0°,0°⟩.
There is also the translation, given in pixels - where the projection center stands relative to the canvas:
projection.translate([point])
If point is specified, sets the projection’s translation offset to the specified two-element array [x, y] and returns the projection. If point is not specified, returns the current translation offset which defaults to [480, 250]. The translation offset determines the pixel coordinates of the projection’s center. The default translation offset places ⟨0°,0°⟩ at the center of a 960×500 area.
When I want to center a feature in the canvas, I like to set the projection center to the center of the feature bounding box - this works for me when using mercator (WGS 84, used in google maps) for my country (Brazil), never tested using other projections and hemispheres. You may have to make adjustments for other situations, but if you nail these basic principles you will be fine.
For example, given a projection and path:
var projection = d3.geo.mercator()
.scale(1);
var path = d3.geo.path()
.projection(projection);
The bounds method from path returns the bounding box in pixels. Use it to find the correct scale, comparing the size in pixels with the size in map units (0.95 gives you a 5% margin over the best fit for width or height). Basic geometry here, calculating the rectangle width/height given diagonally opposed corners:
var b = path.bounds(feature),
s = 0.9 / Math.max(
(b[1][0] - b[0][0]) / width,
(b[1][1] - b[0][1]) / height
);
projection.scale(s);
Use the d3.geo.bounds method to find the bounding box in map units:
b = d3.geo.bounds(feature);
Set the center of the projection to the center of the bounding box:
projection.center([(b[1][0]+b[0][0])/2, (b[1][1]+b[0][1])/2]);
Use the translate method to move the center of the map to the center of the canvas:
projection.translate([width/2, height/2]);
By now you should have the feature in the center of the map zoomed with a 5% margin.
There is a center() method you can use that accepts a lat/lon pair.
From what I understand, translate() is only used for literally moving the pixels of the map. I am not sure how to determine what scale is.
In addition to Center a map in d3 given a geoJSON object, note that you may prefer fitExtent() over fitSize() if you want to specify a padding around the bounds of your object. fitSize() automatically sets this padding to 0.
I was looking around on the Internet for a fuss-free way to center my map, and got inspired by Jan van der Laan and mbostock's answer. Here's an easier way using jQuery if you are using a container for the svg. I created a border of 95% for padding/borders etc.
var width = $("#container").width() * 0.95,
height = $("#container").width() * 0.95 / 1.9 //using height() doesn't work since there's nothing inside
var projection = d3.geo.mercator().translate([width / 2, height / 2]).scale(width);
var path = d3.geo.path().projection(projection);
var svg = d3.select("#container").append("svg").attr("width", width).attr("height", height);
If you looking for exact scaling, this answer won't work for you. But if like me, you wish to display a map that centralizes in a container, this should be enough. I was trying to display the mercator map and found that this method was useful in centralizing my map, and I could easily cut off the Antarctic portion since I didn't need it.
To pan/zoom the map you should look at overlaying the SVG on Leaflet. That will be a lot easier than transforming the SVG. See this example http://bost.ocks.org/mike/leaflet/ and then How to change the map center in leaflet
With mbostocks' answer, and Herb Caudill's comment, I started running into issues with Alaska since I was using a mercator projection. I should note that for my own purposes, I am trying to project and center US States. I found that I had to marry the two answers with Jan van der Laan answer with following exception for polygons that overlap hemispheres (polygons that end up with a absolute value for East - West that is greater than 1):
set up a simple projection in mercator:
projection = d3.geo.mercator().scale(1).translate([0,0]);
create the path:
path = d3.geo.path().projection(projection);
3.set up my bounds:
var bounds = path.bounds(topoJson),
dx = Math.abs(bounds[1][0] - bounds[0][0]),
dy = Math.abs(bounds[1][1] - bounds[0][1]),
x = (bounds[1][0] + bounds[0][0]),
y = (bounds[1][1] + bounds[0][1]);
4.Add exception for Alaska and states that overlap the hemispheres:
if(dx > 1){
var center = d3.geo.centroid(topojson.feature(json, json.objects[topoObj]));
scale = height / dy * 0.85;
console.log(scale);
projection = projection
.scale(scale)
.center(center)
.translate([ width/2, height/2]);
}else{
scale = 0.85 / Math.max( dx / width, dy / height );
offset = [ (width - scale * x)/2 , (height - scale * y)/2];
// new projection
projection = projection
.scale(scale)
.translate(offset);
}
I hope this helps.
For people who want to adjust verticaly et horizontaly, here is the solution :
var width = 300;
var height = 400;
var vis = d3.select("#vis").append("svg")
.attr("width", width).attr("height", height)
d3.json("nld.json", function(json) {
// create a first guess for the projection
var center = d3.geo.centroid(json)
var scale = 150;
var offset = [width/2, height/2];
var projection = d3.geo.mercator().scale(scale).center(center)
.translate(offset);
// create the path
var path = d3.geo.path().projection(projection);
// using the path determine the bounds of the current map and use
// these to determine better values for the scale and translation
var bounds = path.bounds(json);
var hscale = scale*width / (bounds[1][0] - bounds[0][0]);
var vscale = scale*height / (bounds[1][1] - bounds[0][1]);
var scale = (hscale < vscale) ? hscale : vscale;
var offset = [width - (bounds[0][0] + bounds[1][0])/2,
height - (bounds[0][1] + bounds[1][1])/2];
// new projection
projection = d3.geo.mercator().center(center)
.scale(scale).translate(offset);
path = path.projection(projection);
// adjust projection
var bounds = path.bounds(json);
offset[0] = offset[0] + (width - bounds[1][0] - bounds[0][0]) / 2;
offset[1] = offset[1] + (height - bounds[1][1] - bounds[0][1]) / 2;
projection = d3.geo.mercator().center(center)
.scale(scale).translate(offset);
path = path.projection(projection);
// add a rectangle to see the bound of the svg
vis.append("rect").attr('width', width).attr('height', height)
.style('stroke', 'black').style('fill', 'none');
vis.selectAll("path").data(json.features).enter().append("path")
.attr("d", path)
.style("fill", "red")
.style("stroke-width", "1")
.style("stroke", "black")
});
How I centered a Topojson, where I needed to pull out the feature:
var projection = d3.geo.albersUsa();
var path = d3.geo.path()
.projection(projection);
var tracts = topojson.feature(mapdata, mapdata.objects.tx_counties);
projection
.scale(1)
.translate([0, 0]);
var b = path.bounds(tracts),
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);
svg.append("path")
.datum(topojson.feature(mapdata, mapdata.objects.tx_counties))
.attr("d", path)
Currently in d3 if you have a geoJSON object that you are going to draw you have to scale it and translate it in order to get it to the size that one wants and translate it in order to center it. This is a very tedious task of trial and error, and I was wondering if anyone knew a better way to obtain these values?
So for instance if I have this code
var path, vis, xy;
xy = d3.geo.mercator().scale(8500).translate([0, -1200]);
path = d3.geo.path().projection(xy);
vis = d3.select("#vis").append("svg:svg").attr("width", 960).attr("height", 600);
d3.json("../../data/ireland2.geojson", function(json) {
return vis.append("svg:g")
.attr("class", "tracts")
.selectAll("path")
.data(json.features).enter()
.append("svg:path")
.attr("d", path)
.attr("fill", "#85C3C0")
.attr("stroke", "#222");
});
How the hell do I obtain .scale(8500) and .translate([0, -1200]) without going little by little?
My answer is close to Jan van der Laan’s, but you can simplify things slightly because you don’t need to compute the geographic centroid; you only need the bounding box. And, by using an unscaled, untranslated unit projection, you can simplify the math.
The important part of the code is this:
// Create a unit projection.
var projection = d3.geo.albers()
.scale(1)
.translate([0, 0]);
// Create a path generator.
var path = d3.geo.path()
.projection(projection);
// Compute the bounds of a feature of interest, then derive scale & translate.
var b = path.bounds(state),
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];
// Update the projection to use computed scale & translate.
projection
.scale(s)
.translate(t);
After comping the feature’s bounding box in the unit projection, you can compute the appropriate scale by comparing the aspect ratio of the bounding box (b[1][0] - b[0][0] and b[1][1] - b[0][1]) to the aspect ratio of the canvas (width and height). In this case, I’ve also scaled the bounding box to 95% of the canvas, rather than 100%, so there’s a little extra room on the edges for strokes and surrounding features or padding.
Then you can compute the translate using the center of the bounding box ((b[1][0] + b[0][0]) / 2 and (b[1][1] + b[0][1]) / 2) and the center of the canvas (width / 2 and height / 2). Note that since the bounding box is in the unit projection’s coordinates, it must be multiplied by the scale (s).
For example, bl.ocks.org/4707858:
There’s a related question where which is how to zoom to a specific feature in a collection without adjusting the projection, i.e., combining the projection with a geometric transform to zoom in and out. That uses the same principles as above, but the math is slightly different because the geometric transform (the SVG "transform" attribute) is combined with the geographic projection.
For example, bl.ocks.org/4699541:
The following seems to do approximately what you want. The scaling seems to be ok. When applying it to my map there is a small offset. This small offset is probably caused because I use the translate command to center the map, while I should probably use the center command.
Create a projection and d3.geo.path
Calculate the bounds of the current projection
Use these bounds to calculate the scale and translation
Recreate the projection
In code:
var width = 300;
var height = 400;
var vis = d3.select("#vis").append("svg")
.attr("width", width).attr("height", height)
d3.json("nld.json", function(json) {
// create a first guess for the projection
var center = d3.geo.centroid(json)
var scale = 150;
var offset = [width/2, height/2];
var projection = d3.geo.mercator().scale(scale).center(center)
.translate(offset);
// create the path
var path = d3.geo.path().projection(projection);
// using the path determine the bounds of the current map and use
// these to determine better values for the scale and translation
var bounds = path.bounds(json);
var hscale = scale*width / (bounds[1][0] - bounds[0][0]);
var vscale = scale*height / (bounds[1][1] - bounds[0][1]);
var scale = (hscale < vscale) ? hscale : vscale;
var offset = [width - (bounds[0][0] + bounds[1][0])/2,
height - (bounds[0][1] + bounds[1][1])/2];
// new projection
projection = d3.geo.mercator().center(center)
.scale(scale).translate(offset);
path = path.projection(projection);
// add a rectangle to see the bound of the svg
vis.append("rect").attr('width', width).attr('height', height)
.style('stroke', 'black').style('fill', 'none');
vis.selectAll("path").data(json.features).enter().append("path")
.attr("d", path)
.style("fill", "red")
.style("stroke-width", "1")
.style("stroke", "black")
});
With d3 v4 or v5 its getting way easier!
var projection = d3.geoMercator().fitSize([width, height], geojson);
var path = d3.geoPath().projection(projection);
and finally
g.selectAll('path')
.data(geojson.features)
.enter()
.append('path')
.attr('d', path)
.style("fill", "red")
.style("stroke-width", "1")
.style("stroke", "black");
Enjoy, Cheers
I'm new to d3 - will try to explain how I understand it but I'm not sure I got everything right.
The secret is knowing that some methods will operate on the cartographic space (latitude,longitude) and others on the cartesian space (x,y on the screen). The cartographic space (our planet) is (almost) spherical, the cartesian space (screen) is flat - in order to map one over the other you need an algorithm, which is called projection. This space is too short to deep into the fascinating subject of projections and how they distort geographic features in order to turn spherical into plane; some are designed to conserve angles, others conserve distances and so on - there is always a compromise (Mike Bostock has a huge collection of examples).
In d3, the projection object has a center property/setter, given in map units:
projection.center([location])
If center is specified, sets the projection’s center to the specified location, a two-element array of longitude and latitude in degrees and returns the projection. If center is not specified, returns the current center which defaults to ⟨0°,0°⟩.
There is also the translation, given in pixels - where the projection center stands relative to the canvas:
projection.translate([point])
If point is specified, sets the projection’s translation offset to the specified two-element array [x, y] and returns the projection. If point is not specified, returns the current translation offset which defaults to [480, 250]. The translation offset determines the pixel coordinates of the projection’s center. The default translation offset places ⟨0°,0°⟩ at the center of a 960×500 area.
When I want to center a feature in the canvas, I like to set the projection center to the center of the feature bounding box - this works for me when using mercator (WGS 84, used in google maps) for my country (Brazil), never tested using other projections and hemispheres. You may have to make adjustments for other situations, but if you nail these basic principles you will be fine.
For example, given a projection and path:
var projection = d3.geo.mercator()
.scale(1);
var path = d3.geo.path()
.projection(projection);
The bounds method from path returns the bounding box in pixels. Use it to find the correct scale, comparing the size in pixels with the size in map units (0.95 gives you a 5% margin over the best fit for width or height). Basic geometry here, calculating the rectangle width/height given diagonally opposed corners:
var b = path.bounds(feature),
s = 0.9 / Math.max(
(b[1][0] - b[0][0]) / width,
(b[1][1] - b[0][1]) / height
);
projection.scale(s);
Use the d3.geo.bounds method to find the bounding box in map units:
b = d3.geo.bounds(feature);
Set the center of the projection to the center of the bounding box:
projection.center([(b[1][0]+b[0][0])/2, (b[1][1]+b[0][1])/2]);
Use the translate method to move the center of the map to the center of the canvas:
projection.translate([width/2, height/2]);
By now you should have the feature in the center of the map zoomed with a 5% margin.
There is a center() method you can use that accepts a lat/lon pair.
From what I understand, translate() is only used for literally moving the pixels of the map. I am not sure how to determine what scale is.
In addition to Center a map in d3 given a geoJSON object, note that you may prefer fitExtent() over fitSize() if you want to specify a padding around the bounds of your object. fitSize() automatically sets this padding to 0.
I was looking around on the Internet for a fuss-free way to center my map, and got inspired by Jan van der Laan and mbostock's answer. Here's an easier way using jQuery if you are using a container for the svg. I created a border of 95% for padding/borders etc.
var width = $("#container").width() * 0.95,
height = $("#container").width() * 0.95 / 1.9 //using height() doesn't work since there's nothing inside
var projection = d3.geo.mercator().translate([width / 2, height / 2]).scale(width);
var path = d3.geo.path().projection(projection);
var svg = d3.select("#container").append("svg").attr("width", width).attr("height", height);
If you looking for exact scaling, this answer won't work for you. But if like me, you wish to display a map that centralizes in a container, this should be enough. I was trying to display the mercator map and found that this method was useful in centralizing my map, and I could easily cut off the Antarctic portion since I didn't need it.
To pan/zoom the map you should look at overlaying the SVG on Leaflet. That will be a lot easier than transforming the SVG. See this example http://bost.ocks.org/mike/leaflet/ and then How to change the map center in leaflet
With mbostocks' answer, and Herb Caudill's comment, I started running into issues with Alaska since I was using a mercator projection. I should note that for my own purposes, I am trying to project and center US States. I found that I had to marry the two answers with Jan van der Laan answer with following exception for polygons that overlap hemispheres (polygons that end up with a absolute value for East - West that is greater than 1):
set up a simple projection in mercator:
projection = d3.geo.mercator().scale(1).translate([0,0]);
create the path:
path = d3.geo.path().projection(projection);
3.set up my bounds:
var bounds = path.bounds(topoJson),
dx = Math.abs(bounds[1][0] - bounds[0][0]),
dy = Math.abs(bounds[1][1] - bounds[0][1]),
x = (bounds[1][0] + bounds[0][0]),
y = (bounds[1][1] + bounds[0][1]);
4.Add exception for Alaska and states that overlap the hemispheres:
if(dx > 1){
var center = d3.geo.centroid(topojson.feature(json, json.objects[topoObj]));
scale = height / dy * 0.85;
console.log(scale);
projection = projection
.scale(scale)
.center(center)
.translate([ width/2, height/2]);
}else{
scale = 0.85 / Math.max( dx / width, dy / height );
offset = [ (width - scale * x)/2 , (height - scale * y)/2];
// new projection
projection = projection
.scale(scale)
.translate(offset);
}
I hope this helps.
For people who want to adjust verticaly et horizontaly, here is the solution :
var width = 300;
var height = 400;
var vis = d3.select("#vis").append("svg")
.attr("width", width).attr("height", height)
d3.json("nld.json", function(json) {
// create a first guess for the projection
var center = d3.geo.centroid(json)
var scale = 150;
var offset = [width/2, height/2];
var projection = d3.geo.mercator().scale(scale).center(center)
.translate(offset);
// create the path
var path = d3.geo.path().projection(projection);
// using the path determine the bounds of the current map and use
// these to determine better values for the scale and translation
var bounds = path.bounds(json);
var hscale = scale*width / (bounds[1][0] - bounds[0][0]);
var vscale = scale*height / (bounds[1][1] - bounds[0][1]);
var scale = (hscale < vscale) ? hscale : vscale;
var offset = [width - (bounds[0][0] + bounds[1][0])/2,
height - (bounds[0][1] + bounds[1][1])/2];
// new projection
projection = d3.geo.mercator().center(center)
.scale(scale).translate(offset);
path = path.projection(projection);
// adjust projection
var bounds = path.bounds(json);
offset[0] = offset[0] + (width - bounds[1][0] - bounds[0][0]) / 2;
offset[1] = offset[1] + (height - bounds[1][1] - bounds[0][1]) / 2;
projection = d3.geo.mercator().center(center)
.scale(scale).translate(offset);
path = path.projection(projection);
// add a rectangle to see the bound of the svg
vis.append("rect").attr('width', width).attr('height', height)
.style('stroke', 'black').style('fill', 'none');
vis.selectAll("path").data(json.features).enter().append("path")
.attr("d", path)
.style("fill", "red")
.style("stroke-width", "1")
.style("stroke", "black")
});
How I centered a Topojson, where I needed to pull out the feature:
var projection = d3.geo.albersUsa();
var path = d3.geo.path()
.projection(projection);
var tracts = topojson.feature(mapdata, mapdata.objects.tx_counties);
projection
.scale(1)
.translate([0, 0]);
var b = path.bounds(tracts),
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);
svg.append("path")
.datum(topojson.feature(mapdata, mapdata.objects.tx_counties))
.attr("d", path)
Drag and Drop Example
I am trying to rewrite part of this example above to use in my code, specifically this piece:
function centerNode(source) {
scale = zoomListener.scale();
x = -source.y0;
y = -source.x0;
x = x * scale + viewerWidth / 2;
y = y * scale + viewerHeight / 2;
d3.select('g').transition()
.duration(duration)
.attr("transform", "translate(" + x + "," + y + ")scale(" + scale + ")");
zoomListener.scale(scale);
zoomListener.translate([x, y]);
}
However I am getting stuck since the v4 package has changed quite a bit. I wrote my zoomListener function to be
var zoomListener = d3.zoom()
.scaleExtent([0.3,2])
.on("zoom", zoomed);
function zoomed() {
transform = d3.event.transform;
console.log(d3.event);
svg.attr("transform", transform);
}
function centerNode(source){
t = transform;
console.log(t);
x = t.x*t.k; //I only want things to be centered vertically
y = (t.y + -source.x0)*t.k + (viewerHeight)/2 ;
svg.transition()
.duration(duration)
.attr("transform","translate(" + x + "," + y +")scale(" + t.k + ")");
transform.scale(t.k); //DOES NOT WORK
transform.translate([x, y]); //DOES NOT WORK
}
and I know that according to the doc things have changed and info are no longer are stored on what would be my zoomListener
D3 V4 release note on zoom I guess I am just confused on how I am suppose to do it with the new version. The last few lines of my centerNode function don't work which has for effect that when I center the node the zooming and panning reset...
Any suggestion?
So after much digging and trial and error I cam up with an answer that works pretty well for my purposes. Note that this code below is only the relevant part of my code not the whole code, certain variable were self explanatory so did not include them. ALSO THIS IS IN VERSION 4 of d3.js.
var zoom = d3.zoom()
.scaleExtent([0.3,2])
.on("zoom", zoomed);
var svg = d3.select("body")
.append("svg")
.attr("width", viewerWidth)
.attr("height", viewerHeight);
var zoomer = svg.append("rect")
.attr("width", viewerWidth)
.attr("height", viewerHeight)
.style("fill", "none")
.style("pointer-events", "all")
.call(zoom);
var g = svg.append("g");
zoomer.call(zoom.transform, d3.zoomIdentity.translate(150,0)); //This is to pad my svg by a 150px on the left hand side
function zoomed() {
g.attr("transform", d3.event.transform);//The zoom and panning is affecting my G element which is a child of SVG
}
function centerNode(source){
t = d3.zoomTransform(zoomer.node());
console.log(t);
x = t.x;
y = source.x0;
y = -y *t.k + viewerHeight / 2;
g.transition()
.duration(duration)
.attr("transform", "translate(" + x + "," + y + ")scale(" + t.k + ")")
.on("end", function(){ zoomer.call(zoom.transform, d3.zoomIdentity.translate(x,y).scale(t.k))});
}
As per the examples for v4 on the d3.js page, I used a rectangle to apply the zoom to
The zoom behavior is applied to an invisible rect overlaying the SVG
element; this ensures that it receives input, and that the pointer
coordinates are not affected by the zoom behavior’s transform. Pan & Zoom Example
In the Center node function I am using d3.zoomTransform(zoomer.node()); to get the current transform applied to the page.
The purpose of this function is only to center the collapsible tree vertically not horizontally, so I am keeping the current transform.x (here t.x) the same.
The coordinate in my svg are flip hence why y= source.x0, source is a what node was clicked in my collapsible tree. ("Look to the example referenced to the top of this thread to understand what I am trying to convert to version 4)
I am apply the transformation to my G element and then I want to commit those changes to the zoom transform, to do so I use the .on("end", function(){}) otherwise it was doing weird behavior with the transition, by doing that all it does is setting the current state of the transform.
zoomer.call(zoom.transform, d3.zoomIdentity.translate(x,y).scale(t.k))
This line above is applying a translation of x and y and a scale -- that is equal to what the current state -- to the identiy matrix has to get a new transform for G, i then apply it to zoomer which is the element I called zoom on earlier.
This worked like a charm for me!
Calling transform.scale and transform.translate returns a new transform, and modifies nothing. Therefore:
transform = transform.translate([x, y]).scale(k)
svg.call(zoomListener.transform, newTransform)
(At this point zoomListener is a pretty inaccurate name for this, but regardless...)
k, x, and y can be derived from source, maybe as you show, but I'm not sure, because I don't know what source is. But to me, t.x*t.k looks suspicious, because it's multiplying the existing transforms x by its scale. Seems like it would cause a feedback loop.
For more into about the zoom in v4, check out this related StackOverflow post, or this example by mbostock demonstrating programmatic control over the zoom transform of an element (canvas in this case) and includes transitions.
I have three shapes all in the same group. This group have been transformed. I want to draw a line from one of the elements within that group. I am trying to access this elements coordinates by:
s.select("#hitboxHeel").getBBox().cx and s.select("#hitboxHeel").getBBox().cy
However this gives some weird coordinates, that are far off from where they should be. How do i get the actual position of the points, thus being able to draw a line?
I had a similar problem and found the solution from this post : Rectangle coordinates after transform
Here, you basically want to apply the 'aggregated' transform matrix of your shape to coordinates that are not transformed (sorry for the awkward phrasing). This matrix also incorporates the transformations of parent elements (group nodes here), so you shouldn't have to worry about them.
So, given :
your native svg element node
your native svg container svg
your original point of interest coordinates (before transforms) x and y that you want transformed
the expected transformed coordinates of your original point transformedPoint
`
// get the component transform matrix
var ctm = node.getCTM();
var svgPoint = svg.createSVGPoint();
svgPoint.x = x;
svgPoint.y = y;
// apply the matrix to the point
var transformedPoint = svgPoint.matrixTransform(ctm);
// an example using d3.js ( svg > g > rect )
// get the center of the rectangle after tansformations occured
var svg = d3.select('body').append('svg')
.attr('width', 500)
.attr('height', 500)
.attr('id', 'myCanvas')
.style('margin', 100)
var g = svg.append('g')
.attr('transform', 'translate(-10,10)')
var r = g.append('rect')
.attr('x', 300).attr('y', 100).attr('width', 79).attr('height', 150)
.attr('transform', 'translate(-54,300)rotate(-30,30,20)')
.attr('stroke', 'black')
.attr('fill', 'red')
var pt = svg.node().createSVGPoint()
pt.x = parseInt(r.attr('x')) + parseInt(r.attr('width')) / 2
pt.y = parseInt(r.attr('y')) + parseInt(r.attr('height')) / 2
var ctm = r.node().getCTM()
var center = pt.matrixTransform(ctm)
console.log('the transformed rectangle center', center)
// draw the center to confirm the accuracy of the process
svg.append('circle')
.attr('cx', center.x).attr('cy', center.y).attr('r', 5)
.attr('stroke', 'black')
.attr('fill', 'blue')
`