Skip to content

Instantly share code, notes, and snippets.

@ilokhov
Created December 8, 2019 19:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ilokhov/4b7be22c3747694b6ca0c7cc1ec304f6 to your computer and use it in GitHub Desktop.
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
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