Skip to content

Instantly share code, notes, and snippets.

@juanpujol
Last active May 16, 2016 15:57
Show Gist options
  • Save juanpujol/cc84d50cf248796d1d143ede53a5db7e to your computer and use it in GitHub Desktop.
Save juanpujol/cc84d50cf248796d1d143ede53a5db7e to your computer and use it in GitHub Desktop.
Node.js Google Maps geocode API wrapper
'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