简体   繁体   中英

how can I set a height and width for this map in d3.js

I am new and I am working using this map. I have a div container called: #statesvg where I want the map to adapt to its size. but this one is cut.

在此处输入图片说明

in which part of the code can I modify the height and width of the map?

Thank you very much

http://bl.ocks.org/michellechandra/0b2ce4923dc9b5809922

//I get the actual size of the div
var width = document.getElementById('statesvg').offsetWidth;
var height = document.getElementById('statesvg').offsetWidth;
.
.
.
Same code

Other than scaling the entire svg (or portions of it), you can change the projection. The projection determines how much space your features occupy, no matter what the svg size. The easiest method would be to use projection.fitSize() in d3v4+:

projection.fitSize([width,height],feature);

Where width and height are your svg dimensions, and feature is your geojson feature collection ( json in your example, not json.features , it takes an object, not an array). This method sets the scale and translate of the projection so that your features are centered and scaled appropriately for your svg/canvas.

Alternatively, given that all fitSize does is set the translate and scale of a projection, you could modify these attributes directly to set the appropriate scale and translate. Since your example centers the projection with [width/2,height/2] this is will already adapt to provided dimensions. Consequently, all you need to do is set the scale. If the scale value of 1000 is appropriate for a width of 960 and height of 500, then a scale of 2000 will be appropriate for a width of 480 and a height of 250. With this we can just use some simple math:

var scale = 960/width*1000; // assuming that width is always limiting

If width or height could be limiting, find the scale value for both using the above logic and take the higher scale value. Then apply the scale to the map the same as your example does now: projection.scale(scale); . This lets you scale the map easily, and in d3v3 as well (like your example block).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM