| 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 | 2x
 
 
 
 
 
 
2x
 
15x
1x
 
 
14x
1x
 
 
14x
2x
 
 
14x
2x
 
 
14x
 
3x
 
 
11x
 
11x
11x
 
 
2x
2x
2x
 
 
 
 
2x
 
5x
 
 
 
 
 
 
 
5x
 
 
 
5x
 
 
5x
 
 
 
 
2x
5x
 
5x
 
 
 
 
5x
 
 
 
 
 
5x
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2x
5x
 
5x
2x
 
 
3x
 
 
 
 
3x
2x
 
 
 
 
 
 
2x
2x
2x
 
 
 
2x
1x
 
1x
 
 
1x
1x
1x
 
 
1x
1x
 
 
 
 
3x
2x
 
 
2x
 
 
 
 
2x
2x
1x
 
 
 
 
 
 
 
 
 
 
 
 
 
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
 
1x
1x
8x
8x
1x
 
8x
1x
 
8x
1x
 
8x
1x
 
8x
1x
 
8x
1x
 
8x
1x
 
8x
1x
1x
 
 
 
 
1x
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2x
3x
3x
 
3x
 
3x
2x
 
 
 
 
 
 
2x
2x
2x
 
 
 
2x
1x
1x
 
 
1x
1x
 
1x
1x
 
 
 
 
3x
2x
 
 
2x
 
 
 
 
2x | 'use strict';
 
var net = require('net');
 
/**
 * Constructor
 * @param {Object} httpAdapter Http Adapter
 * @param {Object} options     Options (language, client_id, client_secret)
 */
var AGOLGeocoder = function AGOLGeocoder(httpAdapter, options) {
 
  if (!httpAdapter || httpAdapter == 'undefined') {
    throw new Error('ArcGis Online Geocoder requires a httpAdapter to be defined');
  }
 
  if (!options || options == 'undefined') {
    options = {};
  }
 
  if (!options.client_id || options.client_id == 'undefined') {
    options.client_id = null;
  }
 
  if (!options.client_secret || options.client_secret == 'undefined') {
    options.client_secret = null;
  }
 
  if (!options.client_secret || !options.client_id) {
 
    throw new Error('You must specify the client_id and the client_secret');
  }
 
  this.options = options;
 
  this.httpAdapter = httpAdapter;
  this.cache = {};
};
 
AGOLGeocoder.prototype._authEndpoint = 'https://www.arcgis.com/sharing/oauth2/token';
AGOLGeocoder.prototype._endpoint = 'http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/find';
AGOLGeocoder.prototype._reverseEndpoint = 'http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode';
 
//Cached vars
 
 
AGOLGeocoder.prototype._cachedToken = {
  'now': function() {
    return (new Date()).getTime();
  },
  'put': function(token, experation,cache) {
    cache.token = token;
    //Shave 30 secs off experation to ensure that we expire slightly before the actual expiration
    cache.tokenExp = this.now() + (experation - 30);
  },
  'get' : function(cache) {
    Iif(!cache) {
      return null;
    }
 
    Iif(this.now() <= cache.tokenExp) {
      return cache.token;
    } else {
      return null;
    }
  }
};
 
AGOLGeocoder.prototype._getToken = function(callback) {
  var _this = this;
 
  Iif(_this._cachedToken.get(_this.cache) !== null) {
    callback(_this._cachedToken.get());
    return;
    }
 
  var params = {
    'grant_type': 'client_credentials',
    'client_id': _this.options.client_id,
    'client_secret': _this.options.client_secret
  };
 
  _this.httpAdapter.get(_this._authEndpoint, params, function(err, result) {
    if (err) {
      return callback(err);
    } else {
      result = JSON.parse(result);
      var tokenExpiration = (new Date()).getTime() + result.expires_in;
      var token = result.access_token;
      _this._cachedToken.put(token,tokenExpiration,_this.cache);
 
      callback(false, token);
    }
  });
};
 
/**
 * Geocode
 * @param {String}   value    Value to geocode (Address)
 * @param {Function} callback Callback method
 */
AGOLGeocoder.prototype.geocode = function(value, callback) {
  var _this = this;
 
  if (net.isIP(value)) {
    throw new Error('The AGOL geocoder does not support IP addresses');
  }
 
  Iif (value instanceof Array) {
    //As defined in http://resources.arcgis.com/en/help/arcgis-rest-api/#/Batch_geocoding/02r300000003000000/
    throw new Error('An ArcGIS Online organizational account is required to use the batch geocoding functionality');
  }
 
  var execute = function (value,token,callback) {
    var params = {
      'token':token,
      'f':'json',
      'text':value,
      'outFields': 'AddNum,StPreDir,StName,StType,City,Postal,Region,Country'
    };
 
    _this.httpAdapter.get(_this._endpoint, params, function(err, result) {
      result = JSON.parse(result);
        Iif (err) {
          return callback(err);
        } else {
          //This is to work around ESRI's habit of returning 200 OK for failures such as lack of authentication
          if(result.error){
            callback(result.error);
 
            return null;
          }
 
          var results = [];
          for(var i = 0; i < result.locations.length; i++) {
            results.push(_this._formatResult(result.locations[i]));
          }
 
          results.raw = result;
          callback(false, results);
        }
    });
  };
 
  this._getToken(function(err,token) {
    Iif (err) {
      return callback(err);
    } else {
      execute(value,token,callback);
    }
  });
};
 
AGOLGeocoder.prototype._formatResult = function(result) {
  if(result.address){
    return {
      'latitude' : result.location.y,
      'longitude' : result.location.x,
      'country' : result.address.CountryCode,
      'city' : result.address.City,
      'state' : result.address.Region,
      'zipcode' : result.address.Postal,
      'countryCode' : result.address.CountryCode,
      'address': result.address.Address,
      'neighborhood': result.address.Neighborhood,
      'loc_name': result.address.Loc_name
    };
  }
 
  var country = null;
  var countryCode = null;
  var city = null;
  var state = null;
  var stateCode = null;
  var zipcode = null;
  var streetPreDir = null;
  var streetType = null;
  var streetName = null;
  var streetNumber = null;
 
  var attributes = result.feature.attributes;
  for (var property in attributes) {
    Eif (attributes.hasOwnProperty(property)) {
      if(property == 'City') {
        city = attributes[property];
      }
      if(property == 'Postal') {
        zipcode = attributes[property];
      }
      if(property == 'Region') {
        state = attributes[property];
      }
      if(property == 'StPreDir') {
        streetPreDir = attributes[property];
      }
      if(property == 'AddNum') {
        streetNumber = attributes[property];
      }
      if(property == 'StName') {
        streetName = attributes[property];
      }
      if(property == 'StType') {
        streetType = attributes[property];
      }
      if(property == 'Country') {
        countryCode = attributes[property];
        country = attributes[property];
      }
    }
  }
 
  return {
    'latitude' : result.feature.geometry.y,
    'longitude' : result.feature.geometry.x,
    'country' : country,
    'city' : city,
    'state' : state,
    'stateCode' : stateCode,
    'zipcode' : zipcode,
    'streetName': streetPreDir + ' ' + streetName + ' ' + streetType,
    'streetNumber' : streetNumber,
    'countryCode' : countryCode
  };
};
 
/**
 * Reverse geocoding
 * @param {lat:<number>,lon:<number>}  lat: Latitude, lon: Longitude
 * @param {function} callback Callback method
 */
AGOLGeocoder.prototype.reverse = function(query, callback) {
  var lat = query.lat;
  var long = query.lon;
 
  var _this = this;
 
  var execute = function (lat,long,token,callback) {
    var params = {
      'token':token,
      'f':'json',
      'location' : long + ',' + lat,
      'outFields': 'AddrNum,StPreDir,StName,StType,City,Postal,Region,Country'
    };
 
    _this.httpAdapter.get(_this._reverseEndpoint, params, function(err, result) {
      result = JSON.parse(result);
      Iif (err) {
        return callback(err);
      } else {
        //This is to work around ESRI's habit of returning 200 OK for failures such as lack of authentication
        if(result.error){
          callback(result.error,{raw:result});
          return null;
        }
 
        var results = [];
        results.push(_this._formatResult(result));
 
        results.raw = result;
        callback(false, results);
      }
    });
  };
 
  this._getToken(function(err,token) {
    Iif (err) {
      return callback(err);
    } else {
      execute(lat,long,token,callback);
    }
  });
};
 
module.exports = AGOLGeocoder;
  |