Transform GeoJSON to SVG with Javascript

camilokawerin picture camilokawerin · Nov 22, 2011 · Viewed 11.5k times · Source

Is there a ready-to-use Javascript plugin that thansforms a GeoJSON string into a SVG string? A rendering engine, as Tempo, or the project JsonT would be useful, but I need the template to make them works.

Answer

Mr.Hunt picture Mr.Hunt · Jan 30, 2013

You can use d3.js library. Following code snippet will do the job:

Include d3.js in your html file

<script src="files/d3.v3.min.js"></script>

Assuming, you have div with id map in your html file:

<div id="map"></div>

Following js code will add map to your div map. geoJsonObj is your geojson.

var svg = d3.select("#map").append("svg")
            .attr("width", width)
            .attr("height", height);

svg.append("g")
            .selectAll("path")
            .data(geoJsonObj.features)
            .enter().append("path")
            .attr("d", path);

To see a working example, go here. Note that the example uses topojson as input to the .data() attribute.