更新:我已经在答案部分发布并接受了一个完整的解决方案。本节中的任何代码将用作与您自己的非工作代码进行比较的参考,但不能用作解决方案。
我正在建立一个仪表板,并使用d3.js添加一个世界地图,它将根据地理位置实时绘制tweets。
在d3.json()行中引用的world.json文件是可下载的HERE(被称为world-countries.json)。
该地图作为SVG容器在页面上,并使用d3渲染。
下面是相关的代码片段。
- <div id="mapContainer">
- <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="500"></svg>
- </div>
- #mapContainer svg {
- display:block;
- margin:0 auto;
- }
- #mapContainer path {
- fill:#DDD;
- stroke:#FFF;
- }
- // generate US plot
- function draw() {
- var map = d3.select("svg");
- var width = $("svg").parent().width();
- var height = $("svg").parent().height();
- var projection = d3.geo.equirectangular().scale(185).translate([width/2,height/2]);
- var path = d3.geo.path().projection(projection);
- d3.json('plugins/maps/world.json',function(collection) {
- map.selectAll('path').data(collection.features).enter()
- .append('path')
- .attr('d',path)
- .attr("width",width)
- .attr("height",height);
- });
- }
- draw();
- latestLoop();
- $(window).resize(function() {
- draw();
- });
更新:我将地图缩放到可接受的大小(对于我的特定浏览器大小),但是当我更改窗口的大小时,它仍然不会缩放和居中。然而,如果我调整窗口大小,然后点击刷新,那么一旦页面被重新加载,地图就会居中。但是,由于刻度是静态的,因此它不能正确缩放。
解决方法
完整解决方案:
这是在用户释放窗口边缘以调整其大小之后调整映射大小的解决方案,并将其放在父容器中。
- <div id="mapContainer"></div>
- function draw(ht) {
- $("#mapContainer").html("<svg id='map' xmlns='http://www.w3.org/2000/svg' width='100%' height='" + ht + "'></svg>");
- map = d3.select("svg");
- var width = $("svg").parent().width();
- var height = ht;
- // I discovered that the unscaled equirectangular map is 640x360. Thus,we
- // should scale our map accordingly. Depending on the width ratio of the new
- // container,the scale will be this ratio * 100. You could also use the height
- // instead. The aspect ratio of an equirectangular map is 2:1,so that's why
- // our height is half of our width.
- projection = d3.geo.equirectangular().scale((width/640)*100).translate([width/2,width/2);
- });
- }
- draw($("#mapContainer").width()/2);
- $(window).resize(function() {
- if(this.resizeTO) clearTimeout(this.resizeTO);
- this.resizeTO = setTimeout(function() {
- $(this).trigger('resizeEnd');
- },500);
- });
- $(window).bind('resizeEnd',function() {
- var height = $("#mapContainer").width()/2;
- $("#mapContainer svg").css("height",height);
- draw(height);
- });