gpt4 book ai didi

javascript - D3js 世界地图和 svg 组元素宽度出现问题

转载 作者:行者123 更新时间:2023-11-28 04:19:01 26 4
gpt4 key购买 nike

我是 D3js 新手,我正在尝试使用此 jsfiddle 中显示的 d3js 创建世界地图

https://jsfiddle.net/7onjd1pf/

我想要实现的是一个世界地图,它可以根据浏览器的大小调整大小,当您单击一个国家/地区时,会打开一个新的弹出窗口,其中包含该国家/地区的 map 和一些附加信息。

如果我从较大的屏幕尺寸(1000px+)开始并完美地调整大小,无论我有多小,这都可以正常工作。但是,如果我首先在小屏幕上加载页面,则 map 无法正确加载。我观察到,由于某种原因, id 为“countries”的 g 元素总是以 900+ px 的宽度开始,并且不响应内联属性中显示的尺寸。我分配的尺寸确实显示了内联属性,但计算的宽度从其他位置开始,如果我在较小的屏幕尺寸上刷新浏览器,则计算的宽度不会调整到屏幕尺寸。因此,如果我在较小的屏幕尺寸上加载页面, map 显示太大。如果我从大屏幕开始并将窗口大小调整为较小的屏幕,它就可以正常工作。不知道这里发生了什么。有人可以解释一下我如何才能完成这项工作吗?

提前非常感谢您的帮助。

这是代码

HTML:

<

body>
<div class="container">
<div class="row">
<div id="map_container" class="col-xs-12"></div>
<div id="profile" class="col-xs-10">
<div id="country_map" class="col-xs-4"></div>
<button type="button" class="close" aria-label="Close" id="close_map">
<span aria-hidden="true">&times;</span>
</button>
<div id="writeup" class="col-xs-8 of">
<h1>Heading 1</h1>
<p>
<span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure, pariatur, quia! Suscipit voluptas, cumque esse numquam dolore quo maxime blanditiis unde ex pariatur id qui minima autem voluptates ducimus dicta.</span>
<span>Suscipit corporis ex, optio, et libero accusantium dolorum animi. Dolorem unde ratione quas facere eum dolore veritatis ad aliquam repudiandae id expedita minima numquam magnam necessitatibus tenetur nulla, esse soluta!</span>
<span>Voluptas consectetur totam debitis! Et velit alias, quod sed ut labore iusto assumenda numquam, voluptas repellat aliquam quis nemo maxime officiis sunt architecto minus fugit magnam explicabo deleniti voluptates! Accusantium.</span>
<span>Quisquam asperiores, voluptatibus quod incidunt facilis pariatur tenetur quae libero accusantium itaque modi nobis odio. Id pariatur eius doloremque, voluptatem tenetur repudiandae nulla enim sint consectetur vitae non, voluptatibus a.</span>
</p>
</div>
<div id="writeup2" class="col-xs-4">
<h1>Heading 2</h1>
<p>
<span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure, pariatur, quia! Suscipit voluptas, cumque esse numquam dolore quo maxime blanditiis unde ex pariatur id qui minima autem voluptates ducimus dicta.</span>
<span>Suscipit corporis ex, optio, et libero accusantium dolorum animi. Dolorem unde ratione quas facere eum dolore veritatis ad aliquam repudiandae id expedita minima numquam magnam necessitatibus tenetur nulla, esse soluta!</span>
<span>Voluptas consectetur totam debitis! Et velit alias, quod sed ut labore iusto assumenda numquam, voluptas repellat aliquam quis nemo maxime officiis sunt architecto minus fugit magnam explicabo deleniti voluptates! Accusantium.</span>
<span>Quisquam asperiores, voluptatibus quod incidunt facilis pariatur tenetur quae libero accusantium itaque modi nobis odio. Id pariatur eius doloremque, voluptatem tenetur repudiandae nulla enim sint consectetur vitae non, voluptatibus a.</span>
</p>
</div>
<div class="col-xs-8 table-responsive of">
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>City</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Anna</td>
<td>Pitt</td>
<td>35</td>
<td>New York</td>
<td>USA</td>
</tr>
<tr>
<td>2</td>
<td>Bruce</td>
<td>Wayne</td>
<td>35</td>
<td>Gotham</td>
<td>USA</td>
</tr>
<tr>
<td>3</td>
<td>Clarke</td>
<td>Kent</td>
<td>35</td>
<td>Metroplis</td>
<td>USA</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>

CSS:

/*world map*/

#map_container,
#country_map {
height: 80vh;
padding: 20px;
}

.graticule {
fill: none;
stroke: #777;
stroke-width: 0.5px;
stroke-opacity: 0.5;
}

.land {
fill: #222;
}

.boundary {
fill: none;
stroke: #fff;
stroke-width: 0.5px;
}

#profile {
height: 80vh;
background: white;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: none;
overflow: auto;
}

#country_map,
#writeup {
height: 50%;
/*position: relative;
top: 0;
left: 0;*/
}

#writeup2 {
height: 50%;
}

.of {
overflow: auto;
}

[tooltip]:before {
font-family: 'Roboto';
font-weight: 600;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
background-color: #585858;
color: #fff;
content: attr(tooltip);
font-size: 12px;
visibility: hidden;
opacity: 0;
padding: 5px 7px;
margin-right: 10px;
position: absolute;
right: 100%;
bottom: 5%;
white-space: nowrap;
}

[tooltip]:hover:before,
[tooltip]:hover:after {
visibility: visible;
opacity: 1;
}

div.toolTip p {
text-align: left;
}

.toolTip {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
position: absolute;
display: none;
width: auto;
height: auto;
background: none repeat scroll 0 0 white;
border: 0 none;
border-radius: 8px 8px 8px 8px;
box-shadow: -3px 3px 15px #888888;
color: black;
font: 12px sans-serif;
padding: 5px;
text-align: center;
}

JS(已从下面的代码中删除了country_data,但可以在jsfiddle链接中查看):

$(function() {


var data,
map = document.getElementById("map_container"),
inital_width = map.offsetWidth,
map_width = map.offsetWidth,
map_height = map_width * .618,
color = d3.scale.category20c(),
xy = d3
.geo
.mercator()
.translate([map_width / 2, 450]),
path = d3
.geo
.path()
.projection(xy),
svg = d3
.select('#map_container')
.append('svg:svg'),
countries = svg
.append('svg:g')
.attr('id', 'countries');
/* World Map */
function make_map(){
console.log("here")
map_width = map.offsetWidth;
map_height = map_width*.618//map.offsetHeight;

console.log(map_height,map_width,inital_width)

svg
.attr("width",map_width * .9)
.attr("height",map_height * .9);
countries
.attr('width',map_width* .7)
.attr('height',map_height* .7)
.attr("transform", "scale(" + map_width/inital_width + ")");

countries.selectAll('path')
.data(countries_data.features)
.enter()
.append('svg:path')
.attr('d', path)
.attr("class","country")
.attr('fill', "gray")
}
make_map();

var country = d3.selectAll(".country");
var div = d3.select("body").append("div")
.attr("class", "toolTip");

country.on("mousemove",function(d){
d3.select(this).attr({
'fill':"lightblue"
})
div.style("left", d3.event.pageX+10+"px");
div.style("top", d3.event.pageY-25+"px");
div.style("display", "inline-block");
div.html(d.properties.name)
})

country.on("mouseout",function(d){
d3.select(this).attr({
'fill': 'gray'
})
div.style("display", "none");
})

var country_map_div = document.getElementById("country_map"),
profile = $('#profile'),
w2 = profile.width() * 4/12,
h2= profile.height() * .5,
close_map = d3.select("#close_map"),
xy2 = d3.geo.equirectangular(),
selection,
country_map = d3.select("#country_map")
.append('svg:svg')
.attr('width',w2)
.attr('height',h2 )
.attr("id","country_map_svg");

country.on("click", clicked);

function clicked(d){
selection = d;

country_map.selectAll("path").remove();

w2 = profile.width() * 4/12;
h2= profile.height() * .5;

var bounds = path.bounds(d),
dx = bounds[1][0] - bounds[0][0],
dy = bounds[1][1] - bounds[0][1],
x = (bounds[0][0] + bounds[1][0]) / 2,
y = (bounds[0][1] + bounds[1][1]) / 2,
scale = .9 / Math.max(dx / w2, dy / h2),
translate = [w2 / 2 - scale * x, h2 / 2 - scale * y];

country_map
.append("path")
.datum(d)
.attr('id',"c_map")
.attr("d",path)
.attr("fill",function(d) { return color(d.properties.name);})
.attr("transform", "translate(" + translate + ")scale(" + scale + ")");
profile.show(300);
}

close_map.on("click",function(d){
profile.hide();
})


var win = d3.select(window);
win.on("resize", sizeChange);

function sizeChange(element,id) {

map_width = map.offsetWidth;
map_height = map_width * .618;
countries
.attr("transform", "scale(" + map_width/inital_width + ")")
.attr("height",map_height);


var bounds = path.bounds(selection),
dx = bounds[1][0] - bounds[0][0],
dy = bounds[1][1] - bounds[0][1],
x = (bounds[0][0] + bounds[1][0]) / 2,
y = (bounds[0][1] + bounds[1][1]) / 2,
w2 = $("#profile").width() *4/12,
h2 = $("#profile").height()*.5,
scale = .9 / Math.max(dx / w2, dy / h2),
translate = [w2 / 2 - scale * x, h2 / 2 - scale * y];

country_map.attr("width", w2 )
.attr("height", h2)
country_map.select("path")
.attr("transform", "translate(" + translate + ")scale(" + scale + ")");
}

});
PS。提前致歉,将 map 路径所需的所有数据转储放在 js 的顶部。我第一次使用 jsfiddle,无法弄清楚如何将其放入单独的 js 文件中。

最佳答案

第一次添加您的国家/地区时,您没有设置比例。因此,您使用默认比例。 d3 中墨卡托投影的默认比例为 931/Tau (Tau = 2π)。这需要 360 度的地球经度(或 2π 弧度)并将它们水平分布在 961 个像素上。这意味着 map 只能在宽度为 961 像素或以上(或 960 像素,这是 bl.ocks.org 的默认宽度)时正确显示。这解释了这个声明:

This works fine if I start at a larger screen size (1000px+) and resizes perfectly no matter how small I go.

您不是通过重新缩放投影来调整 map 大小,而是通过直接修改 svg 来调整 map 大小,这就是为什么当从像素宽度约为 1000 开始时调整大小在这里起作用的原因

您需要设置投影比例。为此,您需要知道所需的 map 宽度。看起来您想将 g 宽度设置为 svg 宽度的 70%,将 svg 设置为变量 的 90% >map_width,所以你的比例看起来像:

.scale(map_width/(Math.PI*2)*0.9*0.7)

这会将 360 度经度包裹在预期的像素数量上。

注意,您还应该更新投影的 .translate 属性(例如,当前 y 偏移量固定为 450px),因为它也将相对于 map 宽度和高度 -这将使您的 map 在窗口中正确居中。

这是更新的fiddle .

<小时/>

为什么你的弹出功能显示正常?因为您在以下代码中设置了比例(和界限):

    var bounds = path.bounds(d),
dx = bounds[1][0] - bounds[0][0],
dy = bounds[1][1] - bounds[0][1],
x = (bounds[0][0] + bounds[1][0]) / 2,
y = (bounds[0][1] + bounds[1][1]) / 2,
scale = .9 / Math.max(dx / w2, dy / h2),

您可以使用它来正确设置投影,其中至少包括缩放和平移属性。这就是为什么这部分代码与 basemap 相比可以按预期工作。

关于javascript - D3js 世界地图和 svg 组元素宽度出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45596466/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com