d3.js geo - 渲染svg路径

时间:2014-09-22 10:59:18

标签: svg d3.js geojson

我想创建捷克共和国的等值线图。受本文http://bl.ocks.org/mbostock/4060606的启发,我创造了这个 http://jsfiddle.net/1duds8tz/2/

var width = 960;
var height = 500;

var svg = d3.select("body").append("svg").attr("width", width).attr("height", height);
var offset = [width / 2, height / 2];

var projection = d3.geo.mercator().scale(6000).center([15.474, 49.822]).translate(offset);
var path = d3.geo.path().projection(projection);

queue().defer(d3.json, "..map.geojson").await(ready);

function ready(error, reg) {
    var group = svg.selectAll("g").data(reg.features).enter().append("g");
    group.append("path").attr("d", path).attr("fill", "none").attr("stroke", "#222");
}

当我尝试用某种颜色填充svg路径时,我结束了这一点 http://jsfiddle.net/1duds8tz/3/

        group.append("path").attr("d", path).attr("fill", "red").attr("stroke", "#222");

路径d属性中有奇数值。 我的GeoJSON数据必须有点错误,但我无法弄清楚是什么问题。

一切看起来都在这里:https://gist.github.com/anonymous/4e51227dd83be8c2311d

3 个答案:

答案 0 :(得分:3)

您的geoJSON已损坏,因此您的多边形被绘制为无限有界多边形的内部。这就是为什么当你试图给路径填充时,它超出了屏幕的范围,但仍然显示边框很好。我试图颠倒坐标数组的缠绕顺序,这似乎解决了所有这些问题,除了" Brno-venkov",这可能是你问题的根源(特别是考虑到它的管理形状)。 / p>

我建议回到您创建原始GeoJSON的位置,并尝试通过简化重新导出它。如果您想要反转GeoJSON上的坐标以纠正上弦顺序,那很简单:

 geodata = d3.selectAll("path").data();
 for (x in geodata) {geodata[x].geometry.coordinates[0] = geodata[x].geometry.coordinates[0].reverse()}

但这不会修复问题多边形,也不会反转它的坐标。

答案 1 :(得分:0)

如果您熟悉svg操作,可以尝试geojson2svg。这允许您以标准方式操作svg,但您必须编写更多代码。如果您的应用程序需要d3用于许多其他目的,那么d3是最佳解决方案。

答案 2 :(得分:0)

I've got exactly the same problem with Mapzen's .geojson files.

.reverse()-ing isn't good enough, if you can't make sure all your data has the same winding order.

I solved it with this one: https://www.npmjs.com/package/geojson-rewind

  1. You'll need to have npm & require available

  2. Install it, and save it to your project

    npm i -g geojson-rewind

  3. Import it, to make it useable

    var rewind = require('geojson-rewind');

  4. Use it on the data, in this case:

    req = rewind(req);

Tip: If you are working with static data, you can do this only once on the console, and you're good to go.

相关问题