Created
May 29, 2017 06:56
-
-
Save NickCis/921e654f99b7b00f5b87e9125878975e to your computer and use it in GitHub Desktop.
Get city blocks by coordinates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fetch = require('node-fetch'), | |
polygonize = require('polygonize'), | |
interpreterUrl = 'http://overpass-api.de/api/interpreter'; | |
function buildOverpassQL(lat, lon, around='500') { | |
return '[out:json];(' + | |
['primary', 'secondary', 'tertiary', 'residential', 'trunk'].map( | |
e => `way["highway"="${e}"](around:${around}, ${lat}, ${lon});` | |
).join('')+'); out body; >; out skel qt;'; | |
} | |
function toGeoJson(json) { | |
const nodes = json.elements.reduce((prev, now) => { | |
if (now.type == 'node') | |
prev[now.id] = now; | |
return prev; | |
}, {}); | |
const createFeature = (start, end) => { | |
const getCoordinates = id => [ nodes[id].lon, nodes[id].lat ]; | |
return { | |
type: 'Feature', | |
properties: {}, | |
geometry: { | |
type: 'LineString', | |
coordinates: [getCoordinates(start), getCoordinates(end)], | |
} | |
} | |
}; | |
let geoJson = { | |
type: 'FeatureCollection', | |
features: [], | |
}; | |
json.elements.forEach(e => { | |
if (e.type != 'way') | |
return; | |
for (let i=0; i < e.nodes.length -1; i++) { | |
geoJson.features.push(createFeature(e.nodes[i], e.nodes[i+1])); | |
} | |
}); | |
return geoJson; | |
} | |
fetch(interpreterUrl, { method: 'POST', body: `data=${encodeURIComponent(buildOverpassQL('40.798678','-73.966542', 200))}`}) | |
.then(res => res.json()) | |
.then(json => toGeoJson(json)) | |
.then(geoJson => polygonize(geoJson)) | |
.then(geoJson => console.log(JSON.stringify(geoJson))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment