Skip to content

Instantly share code, notes, and snippets.

@javisantana
Last active December 27, 2015 08:59
Show Gist options
  • Save javisantana/7300435 to your computer and use it in GitHub Desktop.
Save javisantana/7300435 to your computer and use it in GitHub Desktop.
quick'n'dirty conversor from OSM xml to GeoJSON using d3
// you should use https://github.com/tyrasd/osmtogeojson if you are gonna build something real
function osm2geojson(xml) {
var parser = new DOMParser();
var doc = parser.parseFromString(xml, 'text/xml');
var points = {}
d3.select(doc).selectAll('node').each(function() {
var n = d3.select(this)
points[n.attr('id')] = [+n.attr('lon'), +n.attr('lat')]
})
var features = [];
d3.select(doc).selectAll('way').each(function() {
var type = "LineString"
var way = d3.select(this)
var refs = []
var properties = {}
way.selectAll('nd').each(function() { refs.push(d3.select(this).attr('ref')) })
way.selectAll('tag').each(function() {
var t = d3.select(this);
properties[t.attr('k')] = t.attr('v');
})
var coordinates = refs.map(function(r) { return points[r]; })
if (refs[0] === refs[refs.length - 1]) {
type = "Polygon"
coordinates = [ coordinates ]
// poygon
}
if( coordinates && coordinates.length) {
features.push({
type: "Feature",
geometry: {
type: type,
coordinates: coordinates
},
properties: properties
})
}
})
return features;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment