[GIS] d3.geo.path() to draw a path from GIS coordinates

d3javascript

Trying to take GIS data of the zip codes of the Bronx and turn it into a map using d3.js. But I am having trouble rendering. Could you show me proper use of d3.geo.path() ?

[ [ -73.84463693999993, 40.90475939500004 ], [ -73.84443733899991, 40.90423928800004 ], [ -73.84443555299993, 40.904234630000076 ], [ -73.84332154899994, 40.90397722300008 ],...]

These numbesr are taken from NYC zip codes map: https://nycopendata.socrata.com/Social-Services/Zip-Codes-Map/zsjh-u7ve

In fact, this question goes for any list of GIS coordinates. How do I turn it into a path? I could not convert the documentation this into code. https://github.com/mbostock/d3/wiki/Geo-Paths

Best Answer

I assume these coordinates trace out a polygon boundary? The easiest thing to do is to turn the coordinate list into GeoJSON

var geoJSON = {
    "type": "FeatureCollection",
    "features":[
        {
            "type":"Feature",
            "geometry":{
                "type":"Polygon",
                "coordinates":[Your list of coordinates]
            },
            "properties":{
                Any associated attributes
            }
        }
    ]
}

Now you create a path generator and use that create your svg for d3.

var path = d3.geo.path();
//Defaults to albersUsa Projection. You might want to set a different one
var width = 960, height = 600;
//Create the svg to render the polygon inside of
var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);
//Bind the geoJSON the path elements in the svg
//Use the enter selection (new elements) and draw the paths using the geo path generator
svg.selectAll("path")
    .data(geoJSON.features)
 .enter().append("path")
    .attr("d",path)
    .attr("fill",#999);
//Note that when you bind new data, you will be changing existing path elements
//So you would also need to do a exit and modify existing paths
Related Question