# All files / lib/geocoder tomtomgeocoder.js

36.36% Statements 8/22
0% Branches 0/6
0% Functions 0/4
36.36% Lines 8/22

    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
    691x
    1x

    1x

    1x

    1x

    1x

    1x

    1x
     var util = require('util');
    var AbstractGeocoder = require('./abstractgeocoder');

    /**
     * Constructor
     * @param <object> httpAdapter Http Adapter
     * @param <object> options     Options (language, clientId, apiKey)
     */
    var TomTomGeocoder = function TomTomGeocoder(httpAdapter, options) {

      TomTomGeocoder.super_.call(this, httpAdapter, options);

      if (!this.options.apiKey || this.options.apiKey == 'undefined') {
        throw new Error('You must specify an apiKey');
      }
    };

    util.inherits(TomTomGeocoder, AbstractGeocoder);

    // TomTom geocoding API endpoint
    TomTomGeocoder.prototype._endpoint = 'http://api.tomtom.com/lbs/geocoding/geocode';

    /**
    * Geocode
    * @param <string>   value    Value to geocode (Address)
    * @param <function> callback Callback method
    */
    TomTomGeocoder.prototype._geocode = function(value, callback) {

      var _this = this;

      var params = {
        query : value,
        key   : this.options.apiKey,
        format: 'json'
      };

      this.httpAdapter.get(this._endpoint, params, function(err, result) {
        if (err) {
          return callback(err);
        } else {
          var results = [];

          for(var i = 0; i < result.geoResponse.geoResult.length; i++) {
              results.push(_this._formatResult(result.geoResponse.geoResult[i]));
          }

          results.raw = result;
          callback(false, results);
        }
      });
    };

    TomTomGeocoder.prototype._formatResult = function(result) {
      return {
        'latitude' : result.latitude,
        'longitude' : result.longitude,
        'country' : result.country,
        'city' : result.city,
        'state' : result.state,
        'zipcode' : result.postcode,
        'streetName': result.street,
        'streetNumber' : result.houseNumber,
        'countryCode' : result.countryISO3
      };
    };

    module.exports = TomTomGeocoder;