d3.js - d3js 缩放、转换和翻译

标签 d3.js

我创建了 nycMap ,一个使用 angularJS (MVC)、yeoman (build)、d3 (mapping) 和 geoJSON (geo data) 的项目。

一切都很好,但我确实需要花费相当多的时间来获得正确的比例和翻译。我想知道如何自动确定 map 将在什么比例下显示最佳以及哪些 x 和 y 值进入翻译?

'use strict';

japanAndCo2App.controller('MainCtrl', function($scope) {

 function makeJapanAll(){
    var path, vis, xy;

    xy = d3.geo.mercator().scale(16000).translate([-5600,2200]);
    path = d3.geo.path().projection(xy);
    vis = d3.select("#japanAll").append("svg:svg").attr("width", 1024).attr("height", 700);
    d3.json("data/JPN_geo4.json", function(json) {
      return vis.append("svg:g")
          .attr("class", "tracts")
          .selectAll("path")
          .data(json.features).enter()
          .append("svg:path")
          .attr("d", path)
          .attr("fill",function(d,i){ return d.properties.color || "transparent"});
    });
  }
  makeJapanAll();
});

(如果你对代码感兴趣,都是 on github 。 map 的代码在 scripts/controllers/main.js 中,与上图相同。)

最佳答案

我也遇到过同样的问题。但是当你有一个边界框时,这很容易做到,它可以从 GeoJSON 中确定(如 meetamit 所说),或者在创建 GeoJson 时。以及想要的 SVG 的宽度。

我将从变量 lattop, lonleft, lonright, width 开始和 height用于 geojson 的边界框和图像的尺寸。我还没有忙于根据纬度差异计算出合适的高度。所以高度只是估计足够大以适合图像。其余的应该从代码中清楚:

var xym = d3.geo.mercator();

// Coordinates of Flanders
var lattop = 51.6;
var lonleft = 2.4;
var lonright = 7.7;
var width = 1500;
var height =1000;

// make the scale so that the difference of longitude is 
// exactly the width of the image
var scale = 360*width/(lonright-lonleft);
xym.scale(scale);

// translate the origin of the map to [0,0] as a start, 
// not to the now meaningless default of [480,250]
xym.translate([0,0]);

// check where your top left coordinate is projected
var trans = xym([lonleft,lattop]);
// translate your map in the negative direction of that result
xym.translate([-1*trans[0],-1*trans[1]]);


var path = d3.geo.path().projection(xym);

var svg = d3.select("body").append("svg").attr("width",width).attr("height",height);

请注意,如果您越过日期变更线(180 度),则必须考虑溢出。

关于d3.js - d3js 缩放、转换和翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13274151/

相关文章:

javascript - 在 D3 map 中显示事件列表

javascript - 如何减少dimple.js中图例矩形和图例文本之间的间距

javascript - 使用相同的数据集绘制各种符号

javascript - 放大水平条形图中的画笔

javascript - dc.js:当计数为零时包括所有条

javascript - D3 : How to draw multiple Convex hulls on Groups of Force layout nodes?

javascript - 文本不显示在 d3js 中的圆圈中间

javascript - 如何更新d3中的子元素?

layout - D3力布局稳定检测

javascript - D3 select multiple tag- 提取值