简体   繁体   English

使用 D3 绘制多边形

[英]Plot polygon using D3

I am trying to plot a polygon using a .json file.我正在尝试使用 .json 文件绘制多边形。

*EDIT to add sample coordinates *编辑以添加样本坐标

{  "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
                ],.....

The script looks like脚本看起来像

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");});

As far as I can tell there is no error but svg doesn't display a thing.据我所知,没有错误,但 svg 没有显示任何内容。 I have also tried methods like scale() center() and offset() .我也尝试过scale() center()offset() Nothing works so far.到目前为止没有任何效果。 This is my first D3 script - do help.这是我的第一个 D3 脚本 - 提供帮助。

Found this D3 polygon Turns out the following code was essential.发现这个D3 多边形原来下面的代码是必不可少的。

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

The complete code is as follows.完整代码如下。

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");
            });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM