how do you adjust the size of a d3js globe?

Projection.scale()

The scale of the projection determines the size of the projected world. Generally speaking d3 projections have a default scale value that will fill a 960×500 SVG/Canvas. A map produced with d3.geoOrthographic doesn’t have a long edge, so this is 500×500 pixels. The default scale value is: 249.5 – half the width/height (allowing for stroke width). This scale factor is linear on both width and height: double it and double both (quadruple projected size of world). So if you want a 200×200 px world you’ll want: 99.5 to be your scale value.

This is the default for d3.geoOrthographic, other scales have other scale defaults. For a Mercator, for example, it is 480/π: 2π of longitude across 960 pixels of width.

Projection.translate()

However, if you change the scale for a 200×200 pixel world, you’ll have an issue with the default projection translate. By default this is set to [250,480] – half of [500,960], the default D3 anticipated size of the SVG/Canvas. This coordinate is where the geographic center of the projection (by default 0°N,0°W) is projected to. You’ll want to change this to a value of [100,100]: the center of your SVG/Canvas.

Solution

const projection = d3.geoOrthographic()
  .scale(99.5)
  .translate([100,100]);

Automagic Solution

There is an easier way, but understanding the mechanics can be useful.

projection.fitSize()/.fitExtent() both set scale and translate automatically based on a specified width/height / extent. In your case this is easy to solve manually, but you could also use:

 d3.geoOrthographic()
   .fitSize([width,height],geoJsonObject)

or

 d3.geoOrthographic()
   .fitExtent([[left,top],[right,bottom]],geojsonObject)

As you’re using topojson: topojson.feature returns a geojson object (with a features property containing individual features – the array of features can’t be passed to fitSize or fitExtent).

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top