-
Notifications
You must be signed in to change notification settings - Fork 0
/
cartong-arcgis-service.js
519 lines (438 loc) · 15.8 KB
/
cartong-arcgis-service.js
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
var CartONG = window.CartONG || {};
$(function() {
var defaultQueryParams = {
where: '1=1',
text: null,
objectIds: null,
time: null,
geometry: null,
geometryType: 'esriGeometryEnvelope',
geometryPrecision: 6,
inSR: null,
outSR: null, //4326,
spatialRel: 'esriSpatialRelIntersects',
relationParam: null,
maxAllowableOffset: null,
outFields: '*',
orderByFields: null,
groupByFieldsForStatistics: null,
outStatistics: null,
gdbVersion: null,
datumTransformation: null,
parameterValue: null,
rangeValues: null,
resultOffset: 0,
resultRecordCount: null,
returnGeometry: true,
returnZ: false,
returnM: false,
returnIdsOnly: false,
returnCountOnly: false,
returnDistinctValues: false,
returnTrueCurves: false,
returnExtentsOnly: false,
queryByDistance: null,
f: 'json' //'geojson'
};
/**
* ArcGIS Service object.
* @constructor
* @param {string or object} opts - The url and other optional parameters.
*/
CartONG.ArcgisService = function (opts) {
//TODO: handle different CRS? different geometry types...
//TODO: handle token (already applied on save function)
//set parameters
if (typeof opts === 'string' && opts != '') {
this.url = opts;
}
else if (opts.url) {
this.url = opts.url;
//TODO: build domain, servicePath and serviceID [low priority]
}
else {
if (!opts.domain || opts.domain == '' || !opts.servicePath || opts.servicePath == '' || !opts.serviceId || opts.serviceId == '') {
console.error('CartONG.ArcgisService.init: not enough parameters to create url, please check you added either url OR domain, servicePath and serviceID.');
return;
}
else {
this.domain = opts.domain;
this.servicePath = opts.servicePath;
this.serviceId = opts.serviceId;
this.url = this.domain + this.servicePath + this.serviceId;
}
}
this.token = opts.token || null;
this.definitionUrl = this.url + '?f=pjson';
this.mapServiceQueryUrl = '/query?where={where}&text=&objectIds={objectIdList}&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=*&returnGeometry=true&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&returnDistinctValues=false&f=pjson';
this.maxIdUrl = this.url + '/query?where=1%3D1&text=&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=4326&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=&returnGeometry=true&maxAllowableOffset=&outSR=4326&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=[{\'statisticType\':\'min\',\'onStatisticField\':\'objectid\',\'outStatisticFieldName\':\'objectid_min\'},{\'statisticType\':\'max\',\'onStatisticField\':\'objectid\',\'outStatisticFieldName\':\'objectid_max\'}]&returnZ=false&returnM=false&gdbVersion=&f=pjson';
opts.name ? this.name = opts.name : null; //console.warn('CartONG.ArcgisService.init: name not available.');
if (opts.attachmentAttributeUrl) {
this.attachmentAttributeService = new CartONG.ArcgisService({
url: opts.attachmentAttributeUrl,
token: this.token
})
}
//this.maxRecordCount = opts.maxRecordCount ? opts.maxRecordCount : ''; //TODO [low priority]: to get maxRecordCount and other meta (SR, geometry type...) from the service itself
//this.definitionPromise = this.loadDefinition();
this.definition;
//TODO: test line below and adapt getMaxRecordCount method
//opts.maxRecordCount ? this.definition = { maxRecordCount: opts.maxRecordCount } : false;
//TODO [low priority]: to get other meta (SR, geometry type...) from the service itself
}
//get parameter functions
CartONG.ArcgisService.prototype.getName = function() {
return (this.name && this.name != '') ? this.name : 'Not available';
}
CartONG.ArcgisService.prototype.getUrl = function() {
return (this.url && this.url != '') ? this.url : 'Not available';
}
CartONG.ArcgisService.prototype.getDomain = function() {
return (this.domain && this.domain != '') ? this.domain : 'Not available';
}
CartONG.ArcgisService.prototype.getServicePath = function() {
return (this.servicePath && this.servicePath != '') ? this.servicePath : 'Not available';
}
CartONG.ArcgisService.prototype.getServiceId = function() {
return (this.serviceId && this.serviceId != '') ? this.serviceId : 'Not available';
}
/*CartONG.ArcgisService.prototype.getMaxRecordCount = function() {
return (this.maxRecordCount && this.maxRecordCount != '') ? this.maxRecordCount : 'Not available';
}*/
CartONG.ArcgisService.prototype.getToken = function() {
//return (this.token && this.token != '') ? this.token : 'Not available';
var t;
if (this.token) {
if (this.token.getToken) {
t = this.token.getToken(); //ArcgisToken.js compatibility
}
else {
t = this.token;
}
}
return t;
}
CartONG.ArcgisService.prototype.setToken = function(token) {
if (!token) {return}
this.token = token;
}
CartONG.ArcgisService.prototype.loadDefinition = function() {
var promise = $.Deferred();
var params = {};
if (this.getToken()) { params.token = this.getToken(); }
$.ajax({
url: this.definitionUrl,
data: params,
dataType: 'json'
})
.done(function(json) {
if (json.error) {
promise.reject({
error: { message: 'Service error: ' + json.error.message + '. Token secured services are not supported yet, coming soon.' }
});
}
else {
this.definition = json;
promise.resolve(json);
}
}.bind(this))
.fail(function(err) {
var msgError = 'Service error'
msgError += (err.status == 404) ? (': ' + err.statusText + '.') : '.' ;
promise.reject({
error: { message: msgError}
});
});
return promise;
}
/**
* Function to download features from the service. Default parameters are used if they are not given as input.
*/
CartONG.ArcgisService.prototype.getData = function(params) {
var promise = $.Deferred();
this.query(params)
.done(function(json) {
if (json.features === undefined) {
promise.reject({
error: { message: 'No features in the result.' }
});
return;
}
//promise.resolve(json.features);
promise.resolve(json);
})
.fail(function(err) {
const msgError = (err.error ? err.error.message : '')
promise.reject({
error: { message: 'Service error' + (msgError != '' ? ': ' + msgError : '' ) + '.' }
});
});
return promise;
}
CartONG.ArcgisService.prototype.getDataByAttribute = function(attribute,params) {
var promise = $.Deferred();
if (attribute.length != 2) {
console.warn('CartONG.ArcgisService.getDataByAttribute: attribute not available.');
return;
}
var queryUrl = setParams(this.mapServiceQueryUrl, {
where: attribute[0] + '+IN+%28%27' + attribute[1].toString() + '%27%29'
});
//var fullUrl = this.url + queryUrl;
//this.query(fullUrl, params)
this.query(queryUrl, params)
.done(function(json) {
if (json.features === undefined) {
promise.reject([]);
return;
}
json = truncateCoordinates(json);
promise.resolve(json.features);
})
.fail(function(err) {
promise.reject(err);
});
return promise;
}
// Query functions
CartONG.ArcgisService.prototype.query = function(params) {
var promise = $.Deferred();
//var queryParams = {}
params = params || {};
params.resultOffset = 0;
this.queryNextFeatures(params, [], promise);
return promise;
}
CartONG.ArcgisService.prototype.queryNextFeatures = function(params, features, promise) {
var maxObjects = (this.definition && this.definition.maxRecordCount) ? this.definition.maxRecordCount : 995;
//const outFormat = params.f
const queryUrl = getEsriURL({
url: this.url,
params: params
});
$.getJSON(queryUrl)
.done(function(res) {
if (res.error) {
//debugger
promise.reject(res)
}
else {
res.features.forEach(function(feature) {
features.push(feature);
});
if (res.features.length === maxObjects) {
params.resultOffset += maxObjects;
this.queryNextFeatures(params, features, promise);
} else {
var output = res;
output.features = features;
promise.resolve(output);
}
}
}.bind(this))
.fail(function(err) {
//debugger
promise.reject(err)
})
}
CartONG.ArcgisService.prototype.features2csv = function(data, format, geometry) {
//TODO: rename this method --> features2array?
var features = [];
var crs;
var geometryType;
if (geometry) {
if (format === 'geojson') {
crs = data.crs.properties.name;
}
else if (format === 'json') {
crs = data.spatialReference ? data.spatialReference.wkid : {};
geometryType = data.geometryType
}
}
data.features.forEach(function(feature) {
var csv;
//var properties = feature.properties || features.attributes
if (format === 'geojson') {
csv = feature.properties;
//TODO: support other geometry types - WKT format?
if (geometry) {
csv.geometryType = feature.geometry.type;
//csv.geometryCoordinates = feature.geometry.coordinates;
csv.x = feature.geometry.coordinates[0];
csv.y = feature.geometry.coordinates[1];
csv.crs = crs;
}
}
else if (format === 'json') {
csv = feature.attributes;
if (geometry) {
csv.geometryType = geometryType;
//csv.geometryCoordinates = feature.geometry;
csv.x = feature.geometry.x;
csv.y = feature.geometry.y;
csv.crs = crs;
}
}
//TODO: trim values
features.push(csv);
//features.push(feature);
});
return features;
}
CartONG.ArcgisService.prototype.export = function(data, format, name) {
var d = new Date().getDate()
var m = new Date().getMonth() + 1 //January is 0!
var y = new Date().getFullYear()
var today = "_" + y + m + d
var filename = "export" + (name ? '_' + name : '') + today
if (format === 'geojson' || format === 'json') {
//data = 'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(data))
data = JSON.stringify(data, undefined, 2)
}
if (format === 'csv' || format === 'geojson' || format === 'json') {
var blob = new Blob(["\ufeff", data])
var url = URL.createObjectURL(blob)
var downloadLink = document.createElement("a")
downloadLink.href = url
downloadLink.download = filename + '.' + format
document.body.appendChild(downloadLink)
downloadLink.click()
document.body.removeChild(downloadLink)
}
/*
else if (format == 'geojson' || format == 'json') {
var dataStr = 'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(data));
var downloadLink = document.createElement('a')
//downloadLink.href = dataStr
//downloadLink.download = filename + ".json"
downloadLink.setAttribute("href", dataStr);
downloadLink.setAttribute("download", filename + ".json");
document.body.appendChild(downloadLink) // required for firefox
downloadLink.click()
downloadLink.remove()
}
*/
}
/**
* CRUD dependency
* TODO: move this to cartong-arcgis-crud
* TODO: allow array input to delete several features at the same time
*/
CartONG.ArcgisService.prototype.delete = function(objectid, callback){
var promise = $.Deferred()
if (!objectid || isNaN(objectid)) {
console.log('CartONG.ArcgisService - delete: param missing');
promise.resolve()
return;
}
var crud = new CRUD(this.url);
var deleteFeature = {
token: this.getToken() ? this.getToken() : '',
feature: Number(objectid)
}
crud.delete(deleteFeature, callback)
.then(function(response) {
handleOutput(response, promise);
})
.fail(function(response) {
handleOutput(response, promise); //TODO: can we replace the following by handleOutput?
//promise.reject({
// success: false,
// error: response[1]
//})
});
return promise
}
/**
* CRUD dependency
* TODO: move this to cartong-arcgis-crud
*/
CartONG.ArcgisService.prototype.save = function(features, action, callback){
var promise = $.Deferred()
if (!features || !features.push || !features.length || !action) {
console.log('CartONG.ArcgisService - save: param missing');
promise.resolve()
return;
}
var crud = new CRUD(this.url);
//var feature_string = JSON.stringify(features);
//encoding added on 5/7/2019. First test went well, to be careful in the next weeks...
var feature_string = encodeURIComponent(JSON.stringify(features));
//console.log(feature_string);
var params = {};
params.feature = feature_string;
//if (this.token) {
params.token = this.getToken() ? this.getToken() : '',
//}
console.log(params);
crud[action](params, callback)
.then(function(response) {
handleOutput(response, promise);
})
.fail(function(response) {
handleOutput(response, promise); //TODO: can we replace the following by handleOutput?
//promise.reject({
// success: false,
// error: response[1]
//})
});
return promise
}
function handleOutput(response, promise) {
switch (response[0]) {
case 1:
case 2:
case 3:
promise.resolve({
success: true,
message: response[1],
item: response[2]
})
break;
case 4:
case 5:
promise.reject({
success: false,
error: response[1]
})
break;
default:
promise.reject({
success: false,
error: 'CRUD: Unexpected error'
})
break;
}
}
/**
* Function to build the url to an arcgis rest service
* @param {object} endpoint Object with url and params attributes. This params attribute is used to build the structure of the query. E.g.: { where: 'iso3={iso3}' }
* @param {*} params Object with params to replace variables in the structure build with previous endpoint object. E.g. { iso3='NPL' }
*/
function getEsriURL(endpoint, params) {
var
query = '',
separator = '',
key, val;
endpoint.params = endpoint.params || {};
for (key in defaultQueryParams) {
val = typeof endpoint.params[key] !== 'undefined' ? endpoint.params[key] : defaultQueryParams[key];
if (val !== '' && val !== null) {
query += separator + key +'='+ encodeURIComponent(setParams(val, params));
separator = '&';
}
}
return setParams(endpoint.url, params) + '/query?' + query;
};
function setParams(str, params) {
//return (str || '').replace(/\{(\w+)\}/g, function(tag, key) {
// return params[key] !== undefined ? params[key] : tag;
//});
if (!params) {
return str;
}
return ('' + str).replace(/\{([^\{\}]+)\}/g, function(t, k) {
return params[k] !== undefined ? params[k] : t;
});
};
});