Created
May 10, 2016 20:13
-
-
Save seanspradlin/f911bdc33ca3dd5f9fcf1258919c2a28 to your computer and use it in GitHub Desktop.
This file contains 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
'use strict'; | |
var querystring = require('querystring'); | |
var request = require('request'); | |
var cert = require('./cert.json'); | |
var GOOGLE_API_PATH = 'https://maps.googleapis.com/maps/api/geocode/json?'; | |
function getCoordinates(address, fn) { | |
var addressStr = stringifyAddress(address); | |
var query = querystring.stringify({ | |
address: addressStr, | |
key: cert.key | |
}); | |
request.get(GOOGLE_API_PATH + query, function getLocation(error, data) { | |
if (error) { | |
fn(error); | |
} else { | |
try { | |
var results = (JSON.parse(data.body)).results[0]; | |
if (results && results.geometry && results.geometry.location) { | |
fn(null, results.geometry.location); | |
} else { | |
fn(new Error('No result found')); | |
} | |
} catch (e) { | |
fn(e); | |
} | |
} | |
}); | |
} | |
function stringifyAddress(address) { | |
var addressStr = ''; | |
addressStr += address.street; | |
addressStr += ' '; | |
addressStr += address.city; | |
addressStr += ' '; | |
addressStr += address.state; | |
addressStr += ' '; | |
addressStr += address.postal; | |
addressStr += ' '; | |
addressStr += address.country; | |
return addressStr; | |
} | |
module.exports = getCoordinates; | |
/** | |
* USAGE | |
*/ | |
var input = { | |
street: '5211 Linbar Drive #507', | |
city: 'Nashville', | |
state: 'TN', | |
postal: '37211', | |
country: 'USA' | |
}; | |
getCoordinates(input, console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment