2014-11-17 05:35:29 +00:00
|
|
|
#!/usr/bin/env node
|
|
|
|
|
|
|
|
var geocoder = require('node-geocoder');
|
|
|
|
var jf = require('jsonfile');
|
|
|
|
var _ = require('underscore');
|
|
|
|
|
|
|
|
|
2014-11-17 05:57:35 +00:00
|
|
|
function queryPosition(gc, address, cache, sequence, callback) {
|
2014-11-17 05:35:29 +00:00
|
|
|
if (_.has(cache, address)) {
|
|
|
|
console.log('Cache lookup success for:\n\t%s', address);
|
|
|
|
callback(cache[address]);
|
2014-11-17 05:57:35 +00:00
|
|
|
return sequence;
|
2014-11-17 05:35:29 +00:00
|
|
|
}
|
|
|
|
|
2014-11-17 05:57:35 +00:00
|
|
|
setTimeout(function() {
|
|
|
|
gc.geocode(address, function(err, res) {
|
|
|
|
if (err) {
|
|
|
|
console.log('Geocode lookup fail for: \n\t%s', address);
|
|
|
|
callback(null);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
console.log('Geocode lookup success for: \n\t%s', address);
|
|
|
|
callback(cache[address] = res[0]);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}, sequence * 200);
|
|
|
|
|
|
|
|
return sequence + 1;
|
2014-11-17 05:35:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
function main() {
|
|
|
|
var gc = geocoder.getGeocoder('google', 'http', {});
|
|
|
|
var srcData = jf.readFileSync('data.json');
|
|
|
|
var srcCount = srcData.length;
|
|
|
|
var cacheData = jf.readFileSync('cache/geo.json', {throws: false}) || {};
|
|
|
|
var destData = [];
|
2014-11-17 05:57:35 +00:00
|
|
|
var sequence = 0;
|
2014-11-17 05:35:29 +00:00
|
|
|
|
|
|
|
_.each(srcData, function(srcItem) {
|
2014-11-17 05:57:35 +00:00
|
|
|
sequence = queryPosition(gc, srcItem.address, cacheData, sequence, function(geo) {
|
2014-11-17 05:35:29 +00:00
|
|
|
if (geo) {
|
|
|
|
var destItem = _.clone(srcItem);
|
|
|
|
destItem.geo = geo;
|
|
|
|
destData.push(destItem);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (--srcCount === 0) {
|
|
|
|
jf.writeFileSync('data.json', destData);
|
|
|
|
jf.writeFileSync('cache/geo.json', cacheData);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
if (require.main === module) {
|
|
|
|
main();
|
|
|
|
}
|