简体   繁体   English

如何在 d3.js 中为这张地图设置高度和宽度

[英]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.我有一个名为: #statesvg的 div 容器,我希望地图适应其大小。 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 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.除了缩放整个 svg(或其中的一部分)之外,您还可以更改投影。 The projection determines how much space your features occupy, no matter what the svg size.无论 svg 大小如何,投影都决定了您的特征占用多少空间。 The easiest method would be to use projection.fitSize() in d3v4+:最简单的方法是在 d3v4+ 中使用projection.fitSize()

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).其中widthheight是您的 svg 尺寸, feature是您的 geojson 特征集合(在您的示例中是json ,而不是json.features ,它需要一个对象,而不是一个数组)。 This method sets the scale and translate of the projection so that your features are centered and scaled appropriately for your svg/canvas.此方法设置投影的比例和平移,以便您的特征居中并为您的 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.或者,鉴于fitSize所做的只是设置投影的平移和缩放,您可以直接修改这些属性以设置适当的缩放和平移。 Since your example centers the projection with [width/2,height/2] this is will already adapt to provided dimensions.由于您的示例将投影以[width/2,height/2]居中[width/2,height/2]这将适应提供的尺寸。 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:如果 1000 的比例值适用于 960 的宽度和 500 的高度,那么 2000 的比例将适用于 480 和 250 的宽度和高度。 有了这个,我们可以使用一些简单的数学:

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);然后将比例应用于地图,就像你现在的例子一样: projection.scale(scale); . . This lets you scale the map easily, and in d3v3 as well (like your example block).这使您可以轻松地缩放地图,并且在 d3v3 中也是如此(就像您的示例块)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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