# All files / lib/geocoder locationiqgeocoder.js

90.77% Statements 59/65
72.73% Branches 24/33
100% Functions 10/10
90.77% Lines 59/65

    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
    2x
    2x
    2x

    2x

    12x

    11x
    1x

    10x

    2x

    2x
    2x

    2x
    4x

    4x
    2x

    2x
    5x
    5x

    5x
    5x

    4x

    4x

    3x

    3x
    3x
    2x
    2x

    2x

    3x

    2x
    2x

    2x
    7x
    7x

    2x

    2x

    2x

    2x
    2x

    2x

    2x

    2x

    4x

    4x
    2x
    2x
    2x
    2x
    2x
    2x
    2x

    2x

    4x

    2x
    6x

    2x
    6x
    6x

    2x
     var
      querystring      = require('querystring'),
      util             = require('util'),
      AbstractGeocoder = require('./abstractgeocoder');

    /**
     * Constructor
     *
     * Geocoder for LocationIQ
     * http://locationiq.org/#docs
     *
     * @param {[type]} httpAdapter [description]
     * @param {String} apiKey      [description]
     */
    var LocationIQGeocoder = function LocationIQGeocoder(httpAdapter, apiKey) {

      LocationIQGeocoder.super_.call(this, httpAdapter);

      if (!apiKey || apiKey == 'undefined') {
        throw new Error('LocationIQGeocoder needs an apiKey');
      }

      this.apiKey = querystring.unescape(apiKey);
    };

    util.inherits(LocationIQGeocoder, AbstractGeocoder);

    LocationIQGeocoder.prototype._endpoint = 'http://locationiq.org/v1';
    LocationIQGeocoder.prototype._endpoint_reverse = 'http://osm1.unwiredlabs.com/locationiq/v1/reverse.php';

    /**
     * Geocode
     * @param  {string|object}   value
     *   Value to geocode (Adress String or parameters as specified over at
     *   http://locationiq.org/#docs)
     * @param  {Function} callback callback method
     */
    LocationIQGeocoder.prototype._geocode = function(value, callback) {
      var params = this._getCommonParams();

      if (typeof value === 'string') {
        params.q = value;
      } else {
        for (var k in value) {
          var v = value[k];
          switch(k) {
            default:
              params[k] = v;
              break;
            // alias for postalcode
            case 'zipcode':
              params.postalcode = v;
              break;
            // alias for street
            case 'address':
              params.street = v;
              break;
          }
        }
      }
      this._forceParams(params);

      this.httpAdapter.get(this._endpoint + '/search.php', params,
        function(err, responseData) {
          Iif (err) {
            return callback(err);
          }

          // when there’s no err thrown here the resulting array object always
          // seemes to be defined but empty so no need to check for
          // responseData.error for now
          // add check if the array is not empty, as it returns an empty array from time to time
          var results = [];
          if (responseData.length && responseData.length > 0) {
            results = responseData.map(this._formatResult).filter(function(result) {
              return result.longitude && result.latitude;
            });
            results.raw = responseData;
          }

          callback(false, results);
        }.bind(this));
    };

    /**
     * Reverse geocoding
     * @param  {lat:<number>,lon<number>}   query    lat: Latitude, lon: Longitutde and additional parameters as specified here: http://locationiq.org/#docs
     * @param  {Function} callback Callback method
     */
    LocationIQGeocoder.prototype._reverse = function(query, callback) {
      var params = this._getCommonParams();

      for (var k in query) {
        var v = query[k];
        params[k] = v;
      }
      this._forceParams(params);

      this.httpAdapter.get(this._endpoint_reverse, params,
        function(err, responseData) {
          Iif (err) {
            return callback(err);
          }

          // when there’s no err thrown here the resulting array object always
          // seemes to be defined but empty so no need to check for
          // responseData.error for now

          // locationiq always seemes to answer with a single object instead
          // of an array
          var results = [responseData].map(this._formatResult).filter(function(result) {
            return result.longitude && result.latitude;
          });
          results.raw = responseData;

          callback(false, results);
        }.bind(this));
    };

    LocationIQGeocoder.prototype._formatResult = function(result) {
      // transform lat and lon to real floats
      var transformedResult = {
        'latitude' : result.lat ? parseFloat(result.lat) : undefined,
        'longitude' : result.lon ? parseFloat(result.lon) : undefined
      };

      if (result.address) {
        transformedResult.country = result.address.country;
        transformedResult.country = result.address.country;
        transformedResult.city = result.address.city || result.address.town || result.address.village || result.address.hamlet;
        transformedResult.state = result.address.state;
        transformedResult.zipcode = result.address.postcode;
        transformedResult.streetName = result.address.road || result.address.cycleway;
        transformedResult.streetNumber = result.address.house_number;
        // make sure countrycode is always uppercase to keep node-geocoder api formats
        transformedResult.countryCode = result.address.country_code.toUpperCase();
      }
      return transformedResult;
    };

    /**
    * Prepare common params
    *
    * @return <Object> common params
    */
    LocationIQGeocoder.prototype._getCommonParams = function() {
      return {
        'key': this.apiKey
      };
    };

    /**
     * Adds parameters that are enforced
     *
     * @param  {object} params object containing the parameters
     */
    LocationIQGeocoder.prototype._forceParams = function(params) {
      params.format = 'json';
      params.addressdetails = '1';
    };

    module.exports = LocationIQGeocoder;