All files / lib/geocoder googlegeocoder.js

85.23% Statements 127/149
85.11% Branches 80/94
100% Functions 9/9
85.23% Lines 127/149
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316    2x 2x 2x 2x             2x 35x   35x   34x 1x     33x         2x     2x             2x   14x 14x   14x 2x   2x 1x     2x 1x 1x   1x     2x 2x 12x     12x     14x 1x     14x 1x     14x 14x   14x 14x 7x     7x     7x         7x 2x     5x   5x   5x 1x     4x     5x 5x             2x 19x       19x 2x     19x 2x     19x 2x 17x 1x     19x       19x 1x     19x       2x   21x 4x 4x   4x 4x 4x 4x   4x   4x     21x     2x   5x             5x                               5x 34x 43x 43x     5x 5x 5x     5x 5x 5x     1x 1x 1x                                     5x 5x     5x 5x   5x 5x   5x 5x                           12x 2x   12x       5x               2x 5x 5x   5x 5x   5x   5x 1x     5x 1x     5x 1x     5x 5x 3x         3x 2x     1x   1x 1x     1x 1x         2x 16x 15x     1x     2x  
'use strict';
 
var crypto = require('crypto');
var url = require('url');
var util = require('util');
var AbstractGeocoder = require('./abstractgeocoder');
 
/**
 * Constructor
 * @param <object> httpAdapter Http Adapter
 * @param <object> options     Options (language, clientId, apiKey, region, excludePartialMatches)
 */
var GoogleGeocoder = function GoogleGeocoder(httpAdapter, options) {
  this.options = ['language', 'apiKey', 'clientId', 'region', 'excludePartialMatches', 'channel'];
 
  GoogleGeocoder.super_.call(this, httpAdapter, options);
 
  if (this.options.clientId && !this.options.apiKey) {
    throw new Error('You must specify a apiKey (privateKey)');
  }
 
  Iif (this.options.apiKey && !httpAdapter.supportsHttps()) {
    throw new Error('You must use https http adapter');
  }
};
 
util.inherits(GoogleGeocoder, AbstractGeocoder);
 
// Google geocoding API endpoint
GoogleGeocoder.prototype._endpoint = 'https://maps.googleapis.com/maps/api/geocode/json';
 
/**
 * Geocode
 * @param <string>   value    Value ton geocode (Address)
 * @param <function> callback Callback method
 */
GoogleGeocoder.prototype._geocode = function (value, callback) {
 
  var _this = this;
  var params = this._prepareQueryString();
 
  if (value.address) {
    var components = null;
 
    if (value.country) {
      components = 'country:' + value.country;
    }
 
    if (value.zipcode) {
      Eif (components) {
        components += '|';
      }
      components += 'postal_code:' + value.zipcode;
    }
 
    params.components = this._encodeSpecialChars(components);
    params.address = this._encodeSpecialChars(value.address);
  } else Iif (value.googlePlaceId) {
    params.place_id = value.googlePlaceId;
  } else {
    params.address = this._encodeSpecialChars(value);
  }
 
  if (value.language) {
    params.language = value.language;
  }
 
  if (value.region) {
    params.region = value.region;
  }
 
  var excludePartialMatches = params.excludePartialMatches;
  delete params.excludePartialMatches;
 
  this._signedRequest(this._endpoint, params);
  this.httpAdapter.get(this._endpoint, params, function (err, result) {
    Iif (err) {
      return callback(err);
    } else {
      var results = [];
      // status can be "OK", "ZERO_RESULTS", "OVER_QUERY_LIMIT", "REQUEST_DENIED", "INVALID_REQUEST", or "UNKNOWN_ERROR"
      // error_message may or may not be present
      Iif (result.status === 'ZERO_RESULTS') {
        results.raw = result;
        return callback(false, results);
      }
 
      if (result.status !== 'OK') {
        return callback(new Error('Status is ' + result.status + '.' + (result.error_message ? ' ' + result.error_message : '')), {raw: result});
      }
 
      for (var i = 0; i < result.results.length; i++) {
 
        var currentResult = result.results[i];
 
        if (excludePartialMatches && excludePartialMatches === true && typeof currentResult.partial_match !== 'undefined' && currentResult.partial_match === true) {
          continue;
        }
 
        results.push(_this._formatResult(currentResult));
      }
 
      results.raw = result;
      callback(false, results);
    }
 
  });
 
};
 
GoogleGeocoder.prototype._prepareQueryString = function () {
  var params = {
    'sensor': false
  };
 
  if (this.options.language) {
    params.language = this.options.language;
  }
 
  if (this.options.region) {
    params.region = this.options.region;
  }
 
  if (this.options.clientId) {
    params.client = this.options.clientId;
  } else if (this.options.apiKey) {
    params.key = this.options.apiKey;
  }
 
  Iif (this.options.channel) {
    params.channel = this.options.channel;
  }
 
  if (this.options.excludePartialMatches && this.options.excludePartialMatches === true) {
    params.excludePartialMatches = true;
  }
 
  return params;
 
};
 
GoogleGeocoder.prototype._signedRequest = function (endpoint, params) {
 
  if (this.options.clientId) {
    var request = url.parse(endpoint);
    var fullRequestPath = request.path + url.format({query: params});
 
    var decodedKey = new Buffer(this.options.apiKey.replace('-', '+').replace('_', '/'), 'base64');
    var hmac = crypto.createHmac('sha1', decodedKey);
    hmac.update(fullRequestPath);
    var signature = hmac.digest('base64');
 
    signature = signature.replace(/\+/g, '-').replace(/\//g, '_');
 
    params.signature = signature;
  }
 
  return params;
};
 
GoogleGeocoder.prototype._formatResult = function (result) {
 
  var googleConfidenceLookup = {
    ROOFTOP: 1,
    RANGE_INTERPOLATED: 0.9,
    GEOMETRIC_CENTER: 0.7,
    APPROXIMATE: 0.5
  };
 
  var extractedObj = {
    formattedAddress: result.formatted_address || null,
    latitude: result.geometry.location.lat,
    longitude: result.geometry.location.lng,
    extra: {
      googlePlaceId: result.place_id || null,
      confidence: googleConfidenceLookup[result.geometry.location_type] || 0,
      premise: null,
      subpremise: null,
      neighborhood: null,
      establishment: null
    },
    administrativeLevels: {
    }
  };
 
  for (var i = 0; i < result.address_components.length; i++) {
    for (var x = 0; x < result.address_components[i].types.length; x++) {
      var addressType = result.address_components[i].types[x];
      switch (addressType) {
        //Country
        case 'country':
          extractedObj.country = result.address_components[i].long_name;
          extractedObj.countryCode = result.address_components[i].short_name;
          break;
        //Administrative Level 1
        case 'administrative_area_level_1':
          extractedObj.administrativeLevels.level1long = result.address_components[i].long_name;
          extractedObj.administrativeLevels.level1short = result.address_components[i].short_name;
          break;
        //Administrative Level 2
        case 'administrative_area_level_2':
          extractedObj.administrativeLevels.level2long = result.address_components[i].long_name;
          extractedObj.administrativeLevels.level2short = result.address_components[i].short_name;
          break;
        //Administrative Level 3
        case 'administrative_area_level_3':
          extractedObj.administrativeLevels.level3long = result.address_components[i].long_name;
          extractedObj.administrativeLevels.level3short = result.address_components[i].short_name;
          break;
        //Administrative Level 4
        case 'administrative_area_level_4':
          extractedObj.administrativeLevels.level4long = result.address_components[i].long_name;
          extractedObj.administrativeLevels.level4short = result.address_components[i].short_name;
          break;
        //Administrative Level 5
        case 'administrative_area_level_5':
          extractedObj.administrativeLevels.level5long = result.address_components[i].long_name;
          extractedObj.administrativeLevels.level5short = result.address_components[i].short_name;
          break;
        // City
        case 'locality':
        case 'postal_town':
          extractedObj.city = result.address_components[i].long_name;
          break;
        // Address
        case 'postal_code':
          extractedObj.zipcode = result.address_components[i].long_name;
          break;
        case 'route':
          extractedObj.streetName = result.address_components[i].long_name;
          break;
        case 'street_number':
          extractedObj.streetNumber = result.address_components[i].long_name;
          break;
        case 'premise':
          extractedObj.extra.premise = result.address_components[i].long_name;
          break;
        case 'subpremise':
          extractedObj.extra.subpremise = result.address_components[i].long_name;
          break;
        case 'establishment':
          extractedObj.extra.establishment = result.address_components[i].long_name;
          break;
        case 'sublocality_level_1':
        case 'political':
        case 'sublocality':
        case 'neighborhood':
          if(!extractedObj.extra.neighborhood) {
            extractedObj.extra.neighborhood = result.address_components[i].long_name;
          }
          break;
      }
    }
  }
  return extractedObj;
};
 
/**
 * Reverse geocoding
 * @param {lat:<number>,lon:<number>}  lat: Latitude, lon: Longitude
 * @param <function> callback Callback method
 */
GoogleGeocoder.prototype._reverse = function (query, callback) {
  var lat = query.lat;
  var lng = query.lon;
 
  var _this = this;
  var params = this._prepareQueryString();
 
  params.latlng = lat + ',' + lng;
 
  if (query.language) {
    params.language = query.language;
  }
 
  if (query.result_type) {
    params.result_type = query.result_type;
  }
 
  if (query.location_type) {
    params.location_type = query.location_type;
  }
 
  this._signedRequest(this._endpoint, params);
  this.httpAdapter.get(this._endpoint, params, function (err, result) {
    Iif (err) {
      return callback(err);
    } else {
      // status can be "OK", "ZERO_RESULTS", "OVER_QUERY_LIMIT", "REQUEST_DENIED", "INVALID_REQUEST", or "UNKNOWN_ERROR"
      // error_message may or may not be present
      if (result.status !== 'OK') {
        return callback(new Error('Status is ' + result.status + '.' + (result.error_message ? ' ' + result.error_message : '')), {raw: result});
      }
 
      var results = [];
 
      Eif (result.results.length > 0) {
        results.push(_this._formatResult(result.results[0]));
      }
 
      results.raw = result;
      callback(false, results);
    }
  });
};
 
GoogleGeocoder.prototype._encodeSpecialChars = function(value) {
  if (typeof value === 'string') {
    return value.replace(/\u001a/g, ' ');
  }
 
  return value;
};
 
module.exports = GoogleGeocoder;