Skip to content

Instantly share code, notes, and snippets.

@emersonbroga
Last active November 25, 2018 14:43
Show Gist options
  • Save emersonbroga/cc34638e59b1293785bc50b421eb4c00 to your computer and use it in GitHub Desktop.
Save emersonbroga/cc34638e59b1293785bc50b421eb4c00 to your computer and use it in GitHub Desktop.
Coordinates from adrress with NodeJs and Google Maps
const request = require('request');
const API_URL = 'https://maps.googleapis.com/maps/api/geocode/json';
const API_KEY = '';
const parseJson = (string) => {
try{
return JSON.parse(string);
}catch(e) {
return null;
}
}
const doRequest = (url) =>{
const promisseCallback = (resolve, reject) => {
request(url, (error, response, body) => {
if (error) reject(error);
const data = parseJson(body);
resolve(data);
});
};
return new Promise(promisseCallback);
}
const getApiUrl = (address) => {
return `${API_URL}?key=${API_KEY}&address=${encodeURI(address)}`;
}
const address = '368 Broadway, New York, NY 10013, USA';
(async () => {
const apiUrl = getApiUrl(address);
const data = await doRequest(apiUrl);
if (!data || data.error_message) {
const message = (data && data.error_message) ? data.error_message : 'Api Error';
console.log(message);
return;
}
console.log(data.results[0].geometry.location);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment