问题
I am trying to plot a polygon using a .json file.
*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. I have also tried methods like scale()
center()
and offset()
. Nothing works so far. This is my first D3 script - do help.
回答1:
Found this D3 polygon
Turns out .attr("points", function (d) {
return d.map;
})
was essential.
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");
});
来源:https://stackoverflow.com/questions/51731404/plot-polygon-using-d3