最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Transform GeoJSON to SVG with Javascript - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Nov 25, 2011 at 19:49 camilokawerin asked Nov 22, 2011 at 22:39 camilokawerincamilokawerin 4011 gold badge3 silver badges14 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 8

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.

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.

You can look into GDAL, not sure if it fully supports SVG creation, but GDAL can generally convert all geo formats into other geoformats.

See: Link

发布评论

评论列表(0)

  1. 暂无评论