Drawing a map with d3js from openstreetmap geojson

Hy

I am trying to draw svg with d3.v3.js from geojson. I am extracting geojson from openstreetmap (my test data: http://pastebin.com/4GQne42i ) and try passing it svg.

My JS code is:

var path, vis, xy, jdata; xy = d3.geo.mercator().translate([0, 0]).scale(200); path = d3.geo.path().projection(xy); vis = d3.select("body").append("svg").attr("width", 960).attr("height", 600); //22.json is the name of the file which contains the geojson data d3.json("22.json", function(error, json) { jdata = json; if(error!=null) console.log(error); return vis.append("svg:g") .selectAll("path") .data(json.coordinates) .enter().append("path") .attr("d", path); }); 

And somehow my svg result is this:

 <svg width="960" height="600"> <g> <path></path> </g> </svg> 

I know projection is not very good, but I think svg should have nodes.

What is the problem with my code? Will you post the right solution?

+4
source share
2 answers

The first problem is the connection:

 vis.append("g") .selectAll("path") .data(json.coordinates) .enter().append("path") .attr("d", path); 

This would mean that you need one path element for each element of the json.coordinates array. Since your test data is polygons, this means one path element for the outer ring, and then maybe several other path elements for any inner holes, if your data has them. I expect you only need one path element for the entire polygon.

The second problem is that you are not passing valid GeoJSON to the d3.geo.path instance. Since the data in your data union is json.coordinates , you simply pass an array of coordinates directly to path when you need to pass a GeoJSON geometry object or function. (See the GeoJSON specification .)

Fortunately, both of these problems are easily fixed by eliminating data merging and rendering of the full polygon. To add only one path element, simply call selection.append :

 vis.append("path") .datum(json) .attr("d", path); 

Your projection will probably need to be adjusted (translated and scaled). You can find the project in the bounding box example .

+4
source

Do you really need to do this with D3?

I would suggest going with more map-oriented libraries, for example:

The sheet vector layer has support for GeoJSON and its size is quite compact.

Open Layers is also an option, but the size is quite large.

Here is an example of how I used Leaflet + GeoJSON to display the suburb shape http://www.geolocation.ws/s/6798/en

+1
source

Source: https://habr.com/ru/post/1480403/


All Articles