Created
May 4, 2016 05:07
-
-
Save t27/99eb85146818695170741dd3a2e0c1fb to your computer and use it in GitHub Desktop.
Geocode a list of cities (or localities) using google's public geocoder. This includes a proper timeout mechanism for sane request intervals. Runs in NodeJS
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
var request = require('request'); | |
var citylist = require('./data/citylist').citylist; // the array of city names | |
var i; | |
var cityDataStore = {}; | |
for (i = 0; i < citylist.length; i++) { | |
if (i < citylist.length) { | |
url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' + citylist[i] + '&sensor=false'; // Max 2500 free requests per IP per Day | |
var currentCity = citylist[i]; | |
(function (city, url, i) { | |
setTimeout(function () { | |
getLocation(city, url, i); | |
}, i * 500);// Calling the function in intervals of 500ms to ensure the server responds correctly | |
})(currentCity, url, i); | |
} | |
} | |
var getLocation = function (currentCity, url, index) { | |
request(url, function (error, response, body) { | |
body = JSON.parse(body || {}); | |
var result = body.results && body.results[0]; // Zero'th result is most probable | |
if (result) { | |
console.log('Storing data for -', currentCity); | |
// Write results to a JSON object store, referenced by currentCity | |
cityDataStore[currentCity] = result; // Or choose to write to a file or DB | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment