Last active
May 16, 2016 15:57
-
-
Save juanpujol/cc84d50cf248796d1d143ede53a5db7e to your computer and use it in GitHub Desktop.
Node.js Google Maps geocode API wrapper
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' | |
const request = require('request-promise'); | |
module.exports = Geocoder; | |
function Geocoder(options) { | |
if(!options.apiKey) { | |
throw new Error('api key is required'); | |
} | |
if (!(this instanceof Geocoder)) { | |
return new Geocoder(); | |
} | |
this.url = 'https://maps.googleapis.com/maps/api/geocode/json'; | |
this.apiKey = options.apiKey; | |
} | |
function validateOptions(options) { | |
if(!options.address && !options.components) { | |
throw new Error('address or components parameters are required'); | |
} | |
} | |
Geocoder.prototype.geocode = function(options) { | |
validateOptions(options); | |
let rOptions = { | |
uri: this.url, | |
qs: { key: this.apiKey }, | |
json: true | |
} | |
if(options.components) { | |
rOptions.qs.components = options.components; | |
} | |
if(options.address) { | |
rOptions.qs.address = options.address; | |
} | |
return request(rOptions); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment