ps0604
ps0604

Reputation: 1081

Fit D3 map in SVG

In this jsfiddle I have a D3 map that I took from here, but I'm trying to fit it in an svg that is half the original size. For that, I changed:

var width = 480;
var height = 300;
.....
var path = d3.geoPath(d3.geoIdentity().translate([width/2, height/2]).scale(height*.5));

But it's not working. How to make the map fit the svg?

Upvotes: 1

Views: 387

Answers (1)

Andrew Reid
Andrew Reid

Reputation: 38211

D3's geoIdentity exposes almost all the standard methods of a d3 projection (off the top of my head, only rotation is not possible as the identity assumes cartesian data). Most importantly here, it exposes the fitSize and fitExtent methods. These methods set translate and scale based on the coordinate extent of displayed geojson data and the pixel extent of the svg/canvas.

To scale your features with a geo identity you can use:

d3.geoIdentity().fitSize([width,height],geojsonObject)

Note that an array of geojson features won't work, but a geojson feature collection or any individual feature/geometry object works too. The width and height are of the svg/canvas.

If you want to apply a margin, you can use:

d3.geoIdentity().fitExtent([[margin,margin],[width-margin,height-margin]],geojsonObject)

The margin doesn't need to be uniform, the format is [[left,top],[right,bottom]],geojsonObject

If using fitSize or fitExtent there is no need to set center, translate or scale manually and setting these afterwards will recenter or rescale the map.

Upvotes: 1

Related Questions