Skip to content

Instantly share code, notes, and snippets.

@qcom
Created June 24, 2014 18:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qcom/51896e0b22939e5bad00 to your computer and use it in GitHub Desktop.
Save qcom/51896e0b22939e5bad00 to your computer and use it in GitHub Desktop.
pull records from postgres that lack a lat/long position value and update accordingly via google's geocoding api
var pg = require('pg');
var request = require('request');
function getUrl(location) {
return 'https://maps.googleapis.com/maps/api/geocode/json?address=' + location.address + ', ' + location.city + ', ' + location.state + ' ' + location.zip_code;
}
var count = 0;
pg.connect(connString, function(err, client, done) {
if (err) throw err;
client.query('SELECT id, address, city, state, zip_code FROM companies WHERE pos IS NULL', function(err, result) {
if (err) throw err;
console.log(result.rows.length + ' to go');
result.rows.forEach(function(company, i) {
request(getUrl(company), function(err, res, body) {
if (err) throw err;
body = JSON.parse(body);
if (body.status == 'OK') {
var location = body.results[0].geometry.location;
client.query('UPDATE companies SET pos = point($1, $2) WHERE id = $3;', [location.lng, location.lat, company.id], function(err, result) {
if (err) throw err;
console.log('Done ' + ++count);
/*console.log(company.id);
console.log(location);
console.log(getUrl(company));*/
if (count === 1500) process.exit();
});
} else {
console.log('ERROR: AT COMPANY ID ' + company.id);
}
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment