Created
December 8, 2019 19:51
-
-
Save ilokhov/4b7be22c3747694b6ca0c7cc1ec304f6 to your computer and use it in GitHub Desktop.
Node.js script for querying city districts for a list of geo coordinates using Nominatim API
This file contains hidden or 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 fs = require('fs'); | |
const request = require('request'); | |
const customHeaderRequest = request.defaults({ | |
headers: { 'User-Agent': 'Reverse geocode search' } | |
}); | |
let output = ''; | |
// expected input format in input_data.csv | |
// is a list of latitude and longitude pairs, for example: | |
// | |
// 52.520856,13.413779 | |
// 52.420140,13.492070 | |
// ... | |
fs.readFile('input_data.csv', (err, data) => { | |
if (err) throw err; | |
const array = data.toString().split('\n'); | |
const lonLats = array.map(item => item.split(',')); | |
const urls = lonLats.map( | |
item => | |
`https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${item[0]}&lon=${item[1]}` | |
); | |
sendRequest(urls); | |
}); | |
function sendRequest(urls) { | |
setTimeout(() => { | |
const url = urls[0]; | |
customHeaderRequest(url, (err, response, body) => { | |
console.log(`request: ${url}`); | |
if (err) throw err; | |
if (!err && response.statusCode === 200) { | |
const data = JSON.parse(body); | |
const district = | |
data.address.city_district || data.address.town; | |
output += `${district}\n`; | |
urls.shift(); | |
if (urls.length === 0) return writeOutput(); | |
sendRequest(urls); | |
} | |
}); | |
}, 1500); | |
} | |
function writeOutput() { | |
fs.writeFile('output_data.csv', output, err => { | |
if (err) throw err; | |
console.log('File written!'); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment