Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform GeoJSON to SVG with Javascript

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.

like image 224
camilokawerin Avatar asked Nov 22 '11 22:11

camilokawerin


2 Answers

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.

like image 157
Mr.Hunt Avatar answered Oct 13 '22 00:10

Mr.Hunt


There is a basic tool available to convert GeoJSON to SVG geojson2svg and as an npm module also. As the output from geojson2svg is SVG string, this tool can be used in browser as well as with node.js.

Here is an example:

npm install geojson2svg --save

var geojson2svg = require('geojson2svg')

var converter = geojson2svg(
   {attributes: ['properties.foo', 'properties.bar', 'properties.baz']})
var svgStr = converter.convert({
  type: 'FeatureCollection',
  features: [{
    type: 'Feature',
    geometry: {type: 'LineString', coordinates: [[0,0], [1000,1000]]},
    properties: {foo: 'fooVal-1', bar: 'barVal-1', baz: 'bazVal-1'}
  }, {
    type: 'Feature',
    geometry: {type: 'LineString', coordinates: [[10,10], [100,100]]},
    properties: {foo: 'fooVal-2', bar: 'barVal-2'}
  }]  
})

console.log(svgStr) 
/* output
[
  '<path d="M128,128 128.00638801979818,127.99361198020182" foo="fooVal-1" bar="barVal-1" baz="bazVal-1"/>',
  '<path d="M128.00006388019798,127.99993611980202 128.00063880197982,127.99936119802018" foo="fooVal-2" bar="barVal-2"/>'
]

*/

It's very easy to covert a SVG string to DOM element. This has been explained by bobince here very nicely with JavaScript code. I have made an npm module for convenience.

Disclaimer: I am the author of geojson2svg.

like image 22
Gagan Avatar answered Oct 13 '22 01:10

Gagan