Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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