-
Notifications
You must be signed in to change notification settings - Fork 116
/
geocoder.ts
424 lines (384 loc) · 11.5 KB
/
geocoder.ts
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
/* Copyright (c) 2017 Environmental Systems Research Institute, Inc.
* Apache-2.0 */
import {
request,
IRequestOptions,
IParams,
warn
} from "@esri/arcgis-rest-request";
// import { IAuthenticatedRequestOptions } from "@esri/arcgis-rest-auth";
import {
IExtent,
ISpatialReference,
IPoint
} from "@esri/arcgis-rest-common-types";
// https always
const worldGeocoder =
"https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/";
// it'd be better if doc didnt display these properties in alphabetical order
export interface IAddressBulk {
/**
* A unique id must be passed along for each individual address.
*/
OBJECTID: number;
address?: string;
address2?: string;
address3?: string;
neighborhood?: string;
city?: string;
subregion?: string;
/**
* The World Geocoding Service considers US states regions.
*/
region?: string;
postal?: number;
postalExt?: number;
countryCode?: string;
}
export interface ILocation {
latitude?: number;
longitude?: number;
lat?: number;
long?: number;
}
function isLocationArray(
coords: ILocation | IPoint | [number, number]
): coords is [number, number] {
return (coords as [number, number]).length === 2;
}
function isLocation(
coords: ILocation | IPoint | [number, number]
): coords is ILocation {
return (
(coords as ILocation).latitude !== undefined ||
(coords as ILocation).lat !== undefined
);
}
export interface IGeocodeParams extends IParams {
/**
* You can create an autocomplete experience by making a call to suggest with partial text and then passing through the magicKey and complete address that are returned to geocode.
* ```js
* import { suggest, geocode } from '@esri/arcgis-rest-geocoder';
* suggest("LAX")
* .then((response) => {
* response.suggestions[2].magicKey; // => "dHA9MCNsb2M9Mjk3ODc2MCNsbmc9MzMjcGw9ODkxNDg4I2xicz0xNDoxNDc4MTI1MA=="
* });
* geocode("LAX, 1 World Way, Los Angeles, CA, 90045, USA", {magicKey: "dHA9MCN..."})
* ```
*/
magicKey?: string;
}
// nice to have: verify custom endpoints contain 'GeocodeServer' and end in a '/'
export interface IEndpointRequestOptions extends IRequestOptions {
/**
* Any ArcGIS Geocoding service (example: http://sampleserver6.arcgisonline.com/arcgis/rest/services/Locators/SanDiego/GeocodeServer )
*/
endpoint?: string;
}
export interface IGeocodeRequestOptions extends IEndpointRequestOptions {
address?: string;
address2?: string;
address3?: string;
neighborhood?: string;
city?: string;
subregion?: string;
/**
* The World Geocoding Service expects US states to be passed in as a 'region'.
*/
region?: string;
postal?: number;
postalExt?: number;
countryCode?: string;
}
export interface ISuggestRequestOptions extends IEndpointRequestOptions {
/**
* You can create an autocomplete experience by making a call to suggest with partial text and then passing through the magicKey and complete address that are returned to geocode.
* ```js
* import { suggest, geocode } from '@esri/arcgis-rest-geocoder';
* suggest("LAX")
* .then((response) => {
* response.suggestions[2].magicKey; // => "dHA9MCNsb2M9Mjk3ODc2MCNsbmc9MzMjcGw9ODkxNDg4I2xicz0xNDoxNDc4MTI1MA=="
* });
* geocode("LAX, 1 World Way, Los Angeles, CA, 90045, USA", {magicKey: "dHA9MCN..."})
* ```
*/
magicKey?: string;
}
export interface IBulkGeocodeRequestOptions extends IEndpointRequestOptions {
addresses: IAddressBulk[];
}
export interface IGeocodeResponse {
spatialReference: ISpatialReference;
candidates: Array<{
address: string;
location: IPoint;
extent: IExtent;
attributes: object;
}>;
}
export interface IReverseGeocodeResponse {
address: {
[key: string]: any;
};
location: IPoint;
}
export interface ISuggestResponse {
suggestions: Array<{
text: string;
magicKey: string;
isCollection: boolean;
}>;
}
export interface IBulkGeocodeResponse {
spatialReference: ISpatialReference;
locations: Array<{
address: string;
location: IPoint;
score: number;
attributes: object;
}>;
}
export interface IGetGeocodeServiceResponse {
currentVersion: number;
serviceDescription: string;
addressFields: any[];
countries: string[];
capabilities: string;
}
/**
* Used to determine the location of a single address or point of interest
*
* ```js
* import { geocode } from '@esri/arcgis-rest-geocoder';
*
* geocode("LAX")
* .then((response) => {
* response.candidates[0].location; // => { x: -118.409, y: 33.943, spatialReference: { wkid: 4326 } }
* });
*
* geocode({
* params: {
* address: "1600 Pennsylvania Ave",
* postal: 20500,
* countryCode: "USA"
* }
* })
* .then((response) => {
* response.candidates[0].location; // => { x: -77.036533, y: 38.898719, spatialReference: { wkid: 4326 } }
* });
* ```
*
* @param address String representing the address or point of interest or RequestOptions to pass to the endpoint.
* @returns A Promise that will resolve with address candidates for the request.
*/
export function geocode(
address: string | IGeocodeRequestOptions
): Promise<IGeocodeResponse> {
let options: IGeocodeRequestOptions = {
endpoint: worldGeocoder,
params: {}
};
if (typeof address === "string") {
options.params.singleLine = address;
} else {
options.endpoint = address.endpoint || worldGeocoder;
options = {
...options,
...address
};
}
// add spatialReference property to individual matches
return request(options.endpoint + "findAddressCandidates", options).then(
response => {
const sr = response.spatialReference;
response.candidates.forEach(function(candidate: {
location: IPoint;
extent: IExtent;
}) {
candidate.location.spatialReference = sr;
candidate.extent.spatialReference = sr;
});
return response;
}
);
}
/**
* Used to return a placename suggestion for a partial string
*
* ```js
* import { suggest } from '@esri/arcgis-rest-geocoder';
*
* suggest("Starb")
* .then((response) => {
* response.address.PlaceName; // => "Starbucks"
* });
* ```
*
* @param requestOptions - Options for the request including authentication and other optional parameters.
* @returns A Promise that will resolve with the data from the response.
*/
export function suggest(
partialText: string,
requestOptions?: ISuggestRequestOptions
): Promise<ISuggestResponse> {
const options: ISuggestRequestOptions = {
endpoint: worldGeocoder,
params: {},
...requestOptions
};
// is this the most concise way to mixin these optional parameters?
if (requestOptions && requestOptions.params) {
options.params = requestOptions.params;
}
if (requestOptions && requestOptions.magicKey) {
options.params.magicKey = requestOptions.magicKey;
}
options.params.text = partialText;
return request(options.endpoint + "suggest", options);
}
/**
* Used to determine the address of a location.
*
* ```js
* import { reverseGeocode } from '@esri/arcgis-rest-geocoder';
*
* // long, lat
* reverseGeocode([-118.409,33.943 ])
* .then((response) => {
* response.address.PlaceName; // => "LA Airport"
* });
*
* // or
* reverseGeocode({ long: -118.409, lat: 33.943 })
* reverseGeocode({ latitude: 33.943, latitude: -118.409 })
* reverseGeocode({ x: -118.409, y: 33.9425 }) // wgs84 is assumed
* reverseGeocode({ x: -13181226, y: 4021085, spatialReference: { wkid: 3857 })
* ```
*
* @param coordinates - the location you'd like to associate an address with.
* @param requestOptions - Additional options for the request including authentication.
* @returns A Promise that will resolve with the data from the response.
*/
export function reverseGeocode(
coords: IPoint | ILocation | [number, number],
requestOptions?: IEndpointRequestOptions
): Promise<IReverseGeocodeResponse> {
const options: IGeocodeRequestOptions = {
endpoint: worldGeocoder,
params: {},
...requestOptions
};
if (isLocationArray(coords)) {
options.params.location = coords.join();
} else if (isLocation(coords)) {
if (coords.lat) {
options.params.location = coords.long + "," + coords.lat;
}
if (coords.latitude) {
options.params.location = coords.longitude + "," + coords.latitude;
}
} else {
// if input is a point, we can pass it straight through, with or without a spatial reference
options.params.location = coords;
}
return request(options.endpoint + "reverseGeocode", options);
}
/**
* Used to geocode a batch of addresses
*
* ```js
* import { bulkGeocode } from '@esri/arcgis-rest-geocoder';
* import { ApplicationSession } from '@esri/arcgis-rest-auth';
*
* const addresses = [
* { "OBJECTID": 1, "SingleLine": "380 New York Street 92373" },
* { "OBJECTID": 2, "SingleLine": "1 World Way Los Angeles 90045" }
* ];
*
* bulkGeocode({ addresses, authentication: session })
* .then((response) => {
* response.locations[0].location; // => { x: -117, y: 34, spatialReference: { wkid: 4326 } }
* });
* ```
*
* @param requestOptions - Request options to pass to the geocoder, including an array of addresses and authentication session.
* @returns A Promise that will resolve with the data from the response.
*/
export function bulkGeocode(
requestOptions: IBulkGeocodeRequestOptions // must POST
) {
// passing authentication is mandatory
const options: IBulkGeocodeRequestOptions = {
endpoint: worldGeocoder,
...requestOptions
};
requestOptions.params = {
forStorage: true,
addresses: { records: null },
...requestOptions.params
};
const parsedAddresses: any[] = [];
requestOptions.addresses.forEach(address => {
parsedAddresses.push({ attributes: address });
});
requestOptions.params.addresses.records = parsedAddresses;
if (!requestOptions.authentication) {
return Promise.reject("bulk geocoding requires authentication");
}
return request(options.endpoint + "geocodeAddresses", requestOptions).then(
response => {
const sr = response.spatialReference;
response.locations.forEach(function(address: { location: IPoint }) {
address.location.spatialReference = sr;
});
return response;
}
);
}
/**
* Used to fetch metadata from a geocoding service.
*
* ```js
* import { getGeocoderServiceInfo } from '@esri/arcgis-rest-geocoder';
*
* getGeocoderServiceInfo()
* .then((response) => {
* response.serviceDescription; // => 'World Geocoder'
* });
* ```
*
* @param requestOptions - Request options can contain a custom geocoding service to fetch metadata from.
* @returns A Promise that will resolve with the data from the response.
*/
export function getGeocodeService(
requestOptions?: IEndpointRequestOptions
): Promise<IGetGeocodeServiceResponse> {
const url = (requestOptions && requestOptions.endpoint) || worldGeocoder;
const options: IEndpointRequestOptions = {
httpMethod: "GET",
maxUrlLength: 2000,
...requestOptions
};
return request(url, options);
}
/**
* Deprecated. Please use `getGeocodeService()` instead.
*
* @param requestOptions - Request options can contain a custom geocoding service to fetch metadata from.
* @returns A Promise that will resolve with the data from the response.
*/
export function serviceInfo(
requestOptions?: IEndpointRequestOptions
): Promise<IGetGeocodeServiceResponse> {
warn(
"serviceInfo() will be deprecated in the next major release. please use getGeocoderServiceInfo() instead."
);
return getGeocodeService(requestOptions);
}
export default {
geocode,
suggest,
reverseGeocode,
bulkGeocode,
serviceInfo
};