使用 D3 绘制面



我正在尝试使用 .json 文件绘制多边形。

*编辑以添加示例坐标

{  "type": "FeatureCollection",  "features": [    {
  "type": "Feature",
  "geometry": {
                "type": "Polygon",
        "coordinates": [
            [
                [
                    -0.0691250297447329,
                    51.5462448874379
                ],
                [
                    -0.0691510961928943,
                    51.5459630404703
                ],
                [
                    -0.0692056531364391,
                    51.5456827414947
                ],
                [
                    -0.0692883661627076,
                    51.5454050640766
                ],
                [
                    -0.0693070134960316,
                    51.545356361588
                ],.....

脚本看起来像

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

    d3.json("/GeoJsonFiles/samplePolygon1.json", function (error, json) {
        if (error) console.error(error);
        var projection = d3.geoMercator()
            .fitSize([width, height], json);
        var path = d3.geoPath().projection(projection);
        svg.selectAll("path")
            .data(json.features)
            .enter()
            .append("path")
            .attr("d", path)
            .attr("fill", "gray")
            .attr("stroke", "black");});

据我所知,没有错误,但 svg 没有显示任何东西。我也尝试过scale() center()offset()等方法。到目前为止没有任何效果。这是我的第一个 D3 脚本 - 请提供帮助。

找到这个 D3 多边形 事实证明,以下代码是必不可少的。

.attr("points", function (d) {
  return d.map;
})

完整代码如下。

d3.json("/GeoJsonFiles/samplePolygon1.json", function (error, json) {
                if (error) console.error(error);
                var projection = d3.geoMercator()
                    .fitSize([width, height], json);
                var path = d3.geoPath().projection(projection);
                svg.selectAll("path")
                    .data([json])
                    .enter()
                    .append("path")
                    .attr("points", function (d) {
                        return d.map;
                    })
                    .attr("d", path)
                    .attr("fill", "gray")
                    .attr("stroke", "black");
            });

最新更新