Weedoze Weedoze - 11 months ago 44
JSON Question

D3 - Map with custom json

I would like to draw a custom map using a json that I will get from a webservice thus not in a file.

The json would probably look like this

"areas" : [
"name" : "A",
"borders" : [[4,50], [4.5,51],...],
"otherProperty" : "red"
"name" : "B",
"borders" : [[3,48] , [3.5,49],...],
"otherProperty" : "yellow"

The borders will draw a polygon that are the borders of the area.

Is it possible to use a Json like this to draw the map ? I can change the json if needed

How can I use this json instead of a file ?

d3.json("myFile.json", function(error, data) {...}


I can use directly


but nothing is displayed and no errors


I am using ConicConformal coordinates for the points



Here is a not-working JSFiddle

Answer Source

I'm not sure I got the point of your question.

It should not matter if the json comes from a file or from a webserver, you can give the path or uri in the d3.json call. Or as you posted in your edit, you can use the variable directly.

The structure you gave can be used without any problems.

I assumed you are using D3 v3. Here you can find the corresponding part of the API documentation. Using this tutorial about svg paths I've created a jsfiddle which displays polygons with the given json-structure (I've changed the numbers to have a more obvious result).

The following function is responsible to get the proper parts of the data you gave when generating the paths which will be used as your polygons' borders.

var lineFunction = d3.svg.line()
                     .x(function(d) { return d[0]; })
                     .y(function(d) { return d[1]; })

And this is how you pass it to the line generator:

.attr("d",function(d) {return lineFunction(d.borders);})

See the fiddle linked above for the complete code.