-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathdata.js
More file actions
4175 lines (3749 loc) · 127 KB
/
data.js
File metadata and controls
4175 lines (3749 loc) · 127 KB
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @fileoverview Singleton for all of the library's communication
* with the Earth Engine API.
* @suppress {missingRequire} TODO(user): this shouldn't be needed
* @suppress {useOfGoogProvide} TODO(user): Convert to goog.module.
*/
goog.provide('ee.data');
goog.provide('ee.data.AssetType');
goog.provide('ee.data.ExportDestination');
goog.provide('ee.data.ExportType');
goog.provide('ee.data.FeatureCollectionDescription');
goog.provide('ee.data.ImageCollectionDescription');
goog.provide('ee.data.ImageDescription');
goog.provide('ee.data.ImageVisualizationParameters');
goog.require('ee.Serializer');
goog.require('ee.api');
goog.require('ee.apiclient');
goog.require('ee.rpc_convert');
goog.require('ee.rpc_convert_batch');
goog.require('goog.array');
goog.require('goog.functions');
goog.require('goog.object');
goog.require('goog.singleton');
goog.requireType('ee.Collection');
goog.requireType('ee.ComputedObject');
goog.requireType('ee.Element');
goog.requireType('ee.Encodable');
goog.requireType('ee.Image');
goog.requireType('ee.data.images');
goog.requireType('proto.google.protobuf.Value');
////////////////////////////////////////////////////////////////////////////////
// Authentication token management. //
////////////////////////////////////////////////////////////////////////////////
/**
* Configures client-side authentication of EE API calls through the
* Google APIs Client Library for JavaScript. The library will be loaded
* automatically if it is not already loaded on the page. The user will be
* asked to grant the application identified by clientId access to their EE
* data if they have not done so previously.
*
* This or another authentication method should be called before
* ee.initialize().
*
* Note that if the user has not previously granted access to the application
* identified by the client ID, by default this will try to pop up a dialog
* window prompting the user to grant the required permission. However, this
* popup can be blocked by the browser. To avoid this, specify the
* opt_onImmediateFailed callback, and in it render an in-page login button,
* then call ee.data.authenticateViaPopup() from the click event handler of
* this button. This stops the browser from blocking the popup, as it is now the
* direct result of a user action.
*
* The auth token will be refreshed automatically when possible. You can safely
* assume that all async calls will be sent with the appropriate credentials.
* For synchronous calls, however, you should check for an auth token with
* ee.data.getAuthToken() and call ee.data.refreshAuthToken() manually if there
* is none. The token refresh operation is asynchronous and cannot be performed
* behind-the-scenes on-demand prior to synchronous calls.
*
* @param {?string} clientId The application's OAuth client ID, or null to
* disable authenticated calls. This can be obtained through the Google
* Developers Console. The project must have a JavaScript origin that
* corresponds to the domain where the script is running.
* @param {function()} success The function to call if authentication succeeded.
* @param {function(string)=} opt_error The function to call if authentication
* failed, passed the error message. If authentication in immediate
* (behind-the-scenes) mode fails and opt_onImmediateFailed is specified,
* that function is called instead of opt_error.
* @param {!Array<string>=} opt_extraScopes Extra OAuth scopes to request.
* @param {function()=} opt_onImmediateFailed The function to call if
* automatic behind-the-scenes authentication fails. Defaults to
* ee.data.authenticateViaPopup(), bound to the passed callbacks.
* @param {boolean=} opt_suppressDefaultScopes When true, only scopes
* specified in opt_extraScopes are requested; the default scopes are not
* requested unless explicitly specified in opt_extraScopes.
* @export
*/
ee.data.authenticateViaOauth = function(
clientId, success, opt_error, opt_extraScopes, opt_onImmediateFailed,
opt_suppressDefaultScopes) {
const scopes = ee.apiclient.mergeAuthScopes(
/* includeDefaultScopes= */ !opt_suppressDefaultScopes,
/* includeStorageScope= */ false, opt_extraScopes || []);
// Remember the auth options.
ee.apiclient.setAuthClient(clientId, scopes);
if (clientId === null) {
ee.apiclient.clearAuthToken();
return;
}
// Start the authentication flow as soon as we have the auth library.
ee.apiclient.ensureAuthLibLoaded(function() {
const onImmediateFailed = opt_onImmediateFailed ||
goog.partial(ee.data.authenticateViaPopup, success, opt_error);
ee.data.refreshAuthToken(success, opt_error, onImmediateFailed);
});
};
/**
* Configures client-side OAuth authentication. Alias of
* ee.data.authenticateViaOauth().
*
* @deprecated Use ee.data.authenticateViaOauth().
* @param {?string} clientId The application's OAuth client ID, or null to
* disable authenticated calls. This can be obtained through the Google
* Developers Console. The project must have a JavaScript origin that
* corresponds to the domain where the script is running.
* @param {function()} success The function to call if authentication succeeded.
* @param {function(string)=} opt_error The function to call if authentication
* failed, passed the error message. If authentication in immediate
* (behind-the-scenes) mode fails and opt_onImmediateFailed is specified,
* that function is called instead of opt_error.
* @param {!Array<string>=} opt_extraScopes Extra OAuth scopes to request.
* @param {function()=} opt_onImmediateFailed The function to call if
* automatic behind-the-scenes authentication fails. Defaults to
* ee.data.authenticateViaPopup(), bound to the passed callbacks.
* @export
*/
ee.data.authenticate = function(
clientId, success, opt_error, opt_extraScopes, opt_onImmediateFailed) {
ee.data.authenticateViaOauth(
clientId, success, opt_error, opt_extraScopes, opt_onImmediateFailed);
};
/**
* Shows a popup asking for the user's permission. Should only be called if
* ee.data.authenticate() called its opt_onImmediateFailed argument in the past.
*
* May be blocked by pop-up blockers if called outside a user-initiated handler.
*
* @param {function()=} opt_success The function to call if authentication
* succeeds.
* @param {function(string)=} opt_error The function to call if authentication
* fails, passing the error message.
* @export
*/
ee.data.authenticateViaPopup = function(opt_success, opt_error) {
const tokenClient =
goog.global['google']['accounts']['oauth2']['initTokenClient']({
'client_id': ee.apiclient.getAuthClientId(),
'callback':
goog.partial(ee.apiclient.handleAuthResult, opt_success, opt_error),
'scope': ee.apiclient.getAuthScopes().join(' '),
});
tokenClient.requestAccessToken();
};
/**
* Configures server-side authentication of EE API calls through the
* Google APIs Node.js Client. Private key authentication is strictly for
* server-side API calls: for browser-based applications, use
* ee.data.authenticateViaOauth(). No user interaction (e.g. authentication
* popup) is necessary when using server-side authentication.
*
* This or another authentication method should be called before
* ee.initialize().
*
* The auth token will be refreshed automatically when possible. You can safely
* assume that all async calls will be sent with the appropriate credentials.
* For synchronous calls, however, you should check for an auth token with
* ee.data.getAuthToken() and call ee.data.refreshAuthToken() manually if there
* is none. The token refresh operation is asynchronous and cannot be performed
* behind-the-scenes, on demand, prior to synchronous calls.
*
* @param {!ee.data.AuthPrivateKey} privateKey JSON content of private key.
* @param {function()=} opt_success The function to call if authentication
* succeeded.
* @param {function(string)=} opt_error The function to call if authentication
* failed, passed the error message.
* @param {!Array<string>=} opt_extraScopes Extra OAuth scopes to request.
* @param {boolean=} opt_suppressDefaultScopes When true, only scopes
* specified in opt_extraScopes are requested; the default scopes are not
* not requested unless explicitly specified in opt_extraScopes.
* @export
*/
ee.data.authenticateViaPrivateKey = function(
privateKey, opt_success, opt_error, opt_extraScopes,
opt_suppressDefaultScopes) {
// Verify that the context is Node.js, not a web browser.
if ('window' in goog.global) {
throw new Error(
'Use of private key authentication in the browser is insecure. ' +
'Consider using OAuth, instead.');
}
const scopes = ee.apiclient.mergeAuthScopes(
/* includeDefaultScopes= */ !opt_suppressDefaultScopes,
/* includeStorageScope= */ !opt_suppressDefaultScopes,
opt_extraScopes || []);
ee.apiclient.setAuthClient(privateKey.client_email, scopes);
// Initialize JWT client to authorize as service account.
const jwtClient = new google.auth.JWT(
privateKey.client_email, null, privateKey.private_key, scopes, null);
// Configure authentication refresher to use JWT client.
ee.data.setAuthTokenRefresher(function(authArgs, callback) {
jwtClient.authorize(function(error, token) {
if (error) {
callback({'error': error});
} else {
callback({
'access_token': token.access_token,
'token_type': token.token_type,
'expires_in': (token.expiry_date - Date.now()) / 1000,
});
}
});
});
ee.data.refreshAuthToken(opt_success, opt_error);
};
ee.data.setApiKey = ee.apiclient.setApiKey;
ee.data.setProject = ee.apiclient.setProject;
ee.data.getProject = ee.apiclient.getProject;
/** @const {string} */
ee.data.PROFILE_REQUEST_HEADER = ee.apiclient.PROFILE_REQUEST_HEADER;
/**
* Sets a function used to transform expressions potentially adding metadata.
*
* @param {?function(!ee.api.Expression, !Object=): !ee.api.Expression}
* augmenter A function used to transform the expression parameters right
* before they are sent to the server.
*/
ee.data.setExpressionAugmenter = function(augmenter) {
ee.data.expressionAugmenter_ = augmenter || goog.functions.identity;
};
goog.exportSymbol(
'ee.data.setExpressionAugmenter', ee.data.setExpressionAugmenter);
/**
* A function used to transform expression right before they are sent to the
* server. Takes in an expression to annotate and any extra metadata to attach
* to the expression.
* @private {function(?ee.api.Expression, !Object=):?ee.api.Expression}
*/
ee.data.expressionAugmenter_ = goog.functions.identity;
////////////////////////////////////////////////////////////////////////////////
// Re-exported imports from ee.apiclient //
////////////////////////////////////////////////////////////////////////////////
// The following symbols are exported for the benefit of users who create tokens
// server side but initialize the API client side.
ee.data.setAuthToken = ee.apiclient.setAuthToken;
goog.exportSymbol('ee.data.setAuthToken', ee.data.setAuthToken);
ee.data.refreshAuthToken = ee.apiclient.refreshAuthToken;
goog.exportSymbol('ee.data.refreshAuthToken', ee.data.refreshAuthToken);
ee.data.setAuthTokenRefresher = ee.apiclient.setAuthTokenRefresher;
goog.exportSymbol(
'ee.data.setAuthTokenRefresher', ee.data.setAuthTokenRefresher);
ee.data.getAuthToken = ee.apiclient.getAuthToken;
goog.exportSymbol('ee.data.getAuthToken', ee.data.getAuthToken);
ee.data.clearAuthToken = ee.apiclient.clearAuthToken;
goog.exportSymbol('ee.data.clearAuthToken', ee.data.clearAuthToken);
ee.data.getAuthClientId = ee.apiclient.getAuthClientId;
goog.exportSymbol('ee.data.getAuthClientId', ee.data.getAuthClientId);
ee.data.getAuthScopes = ee.apiclient.getAuthScopes;
goog.exportSymbol('ee.data.getAuthScopes', ee.data.getAuthScopes);
ee.data.setDeadline = ee.apiclient.setDeadline;
goog.exportSymbol('ee.data.setDeadline', ee.data.setDeadline);
// The following symbol is exported because it is used in the Code Editor, much
// like ee.data.setExpressionAugmenter above is.
ee.data.setParamAugmenter = ee.apiclient.setParamAugmenter;
goog.exportSymbol('ee.data.setParamAugmenter', ee.data.setParamAugmenter);
// The following symbols are not exported because they are meant to be used via
// the wrapper functions in ee.js.
/** @type {function(?string=,?string=,?string=,?string=)} */
ee.data.initialize = ee.apiclient.initialize;
/** @type {function()} */
ee.data.reset = ee.apiclient.reset;
// The following symbols are not exported because they are meant for internal
// use only.
/** @const {string} */
ee.data.PROFILE_HEADER = ee.apiclient.PROFILE_HEADER;
ee.data.makeRequest_ = ee.apiclient.makeRequest;
ee.data.send_ = ee.apiclient.send;
ee.data.setupMockSend = ee.apiclient.setupMockSend;
ee.data.withProfiling = ee.apiclient.withProfiling;
////////////////////////////////////////////////////////////////////////////////
// Main computation entry points. //
////////////////////////////////////////////////////////////////////////////////
/**
* Get the list of algorithms.
*
* @param {function(?ee.data.AlgorithmsRegistry, string=)=} opt_callback
* An optional callback. If not supplied, the call is made synchronously.
* @return {?ee.data.AlgorithmsRegistry} The list of algorithm
* signatures, or null if a callback is specified.
*/
ee.data.getAlgorithms = function(opt_callback) {
const call = new ee.apiclient.Call(opt_callback);
return call.handle(call.algorithms()
.list(call.projectsPath(), {prettyPrint: false})
.then(ee.rpc_convert.algorithms));
};
/**
* Get a Map ID for a given asset
* @param {!ee.data.ImageVisualizationParameters} params
* The visualization parameters as a (client-side) JavaScript object.
* For Images and ImageCollections:
* <table>
* <tr>
* <td><code> image </code> (JSON string) The image to render.</td>
* </tr>
* <tr>
* <td><code> version </code> (number) Version number of
* image (or latest).</td>
* </tr>
* <tr>
* <td><code> bands </code> (comma-separated strings) Comma-delimited
* list of band names to be mapped to RGB.</td>
* </tr>
* <tr>
* <td><code> min </code> (comma-separated numbers) Value (or one
* per band) to map onto 00.</td>
* </tr>
* <tr>
* <td><code> max </code> (comma-separated numbers) Value (or one
* per band) to map onto FF.</td>
* </tr>
* <tr>
* <td><code> gain </code> (comma-separated numbers) Gain (or one
* per band) to map onto 00-FF.</td>
* </tr>
* <tr>
* <td><code> bias </code> (comma-separated numbers) Offset (or one
* per band) to map onto 00-FF.</td>
* </tr>
* <tr>
* <td><code> gamma </code> (comma-separated numbers) Gamma correction
* factor (or one per band).</td>
* </tr>
* <tr>
* <td><code> palette </code> (comma-separated strings) List of
* CSS-style color strings (single-band previews only).</td>
* </tr>
* <tr>
* <td><code> opacity </code> (number) a number between 0 and 1 for
* opacity.</td>
* </tr>
* <tr>
* <td><code> format </code> (string) Either "jpg" or "png".</td>
* </tr>
* </table>
* @param {function(?ee.data.RawMapId, string=)=} opt_callback
* An optional callback. If not supplied, the call is made synchronously.
* @return {?ee.data.RawMapId} The mapId call results, which may be passed to
* ee.data.getTileUrl or ui.Map.addLayer. Null if a callback is specified.
* @export
*/
ee.data.getMapId = function(params, opt_callback) {
if (typeof params.image === 'string') {
throw new Error('Image as JSON string not supported.');
}
if (params.version !== undefined) {
throw new Error('Image version specification not supported.');
}
const map = new ee.api.EarthEngineMap({
name: null,
expression: ee.data.expressionAugmenter_(
ee.Serializer.encodeCloudApiExpression(params.image)),
fileFormat: ee.rpc_convert.fileFormat(params.format),
bandIds: ee.rpc_convert.bandList(params.bands),
visualizationOptions: ee.rpc_convert.visualizationOptions(params),
});
const queryParams = {fields: 'name'};
const workloadTag = ee.data.getWorkloadTag();
if (workloadTag) {
queryParams.workloadTag = workloadTag;
}
const getResponse = (response) => ee.data.makeMapId_(response['name'], '');
const call = new ee.apiclient.Call(opt_callback);
return call.handle(call.maps()
.create(call.projectsPath(), map, queryParams)
.then(getResponse));
};
/**
* Generate a URL for map tiles from a Map ID and coordinates.
* If formatTileUrl is not present, we generate it by using or guessing the
* urlFormat string, and add urlFormat and formatTileUrl to `id` for future use.
* @param {!ee.data.RawMapId} id The Map ID to generate tiles for.
* @param {number} x The tile x coordinate.
* @param {number} y The tile y coordinate.
* @param {number} z The tile zoom level.
* @return {string} The tile URL.
* @export
*/
ee.data.getTileUrl = function(id, x, y, z) {
if (!id.formatTileUrl) {
// If formatTileUrl does not exist, the caller may have constructed mapid
// explicitly (such as from a JSON response). Look for a url format string,
// and finally fall back to setting the format string based on the current
// API version.
const newId = ee.data.makeMapId_(id.mapid, id.token, id.urlFormat);
id.urlFormat = newId.urlFormat; // Set for reference.
id.formatTileUrl = newId.formatTileUrl;
}
return id.formatTileUrl(x, y, z);
};
/**
* Constructs a RawMapId, generating formatTileUrl and urlFormat from mapid and
* token.
* @param {string} mapid Map ID.
* @param {string} token Token. Will only be non-empty when using legacy API.
* @param {string=} opt_urlFormat Explicit URL format. Overrides the format
* inferred from mapid and token.
* @return {!ee.data.RawMapId}
* @private
*/
ee.data.makeMapId_ = function(mapid, token, opt_urlFormat = '') {
let urlFormat = opt_urlFormat;
if (!urlFormat) {
ee.apiclient.initialize();
const base = ee.apiclient.getTileBaseUrl();
const args = '{z}/{x}/{y}'; // Named substitutions for Python API parity.
if (token) {
// Legacy form where token is populated.
urlFormat = `${base}/map/${mapid}/${args}?token=${token}`;
} else {
urlFormat = `${base}/${ee.apiclient.VERSION}/${mapid}/tiles/${args}`;
}
}
const formatTileUrl = (x, y, z) => {
const width = Math.pow(2, z);
x = x % width;
x = String(x < 0 ? x + width : x); // JSCompiler: replace() needs string.
return urlFormat.replace('{x}', x).replace('{y}', y).replace('{z}', z);
};
return {mapid, token, formatTileUrl, urlFormat};
};
/**
* Get a tiles key for a given map or asset. The tiles key can be passed to an
* instance of FeatureViewTileSource which can be rendered on a base map outside
* of the Code Editor.
* @param {!ee.data.FeatureViewVisualizationParameters} params
* The visualization parameters as a (client-side) JavaScript object.
* For FeatureView assets:
* <table>
* <tr>
* <td><code> assetId </code> (string) The asset ID for which to
* obtain a tiles key.</td>
* </tr>
* <tr>
* <td><code> visParams </code> (Object) The visualization parameters
* for this layer.</td>
* </tr>
* </table>
* @param {function(?ee.data.FeatureViewTilesKey, string=)=} opt_callback An
* optional callback. If not supplied, the call is made synchronously.
* @return {?ee.data.FeatureViewTilesKey} The call results. Null if a callback
* is specified.
* @export
*/
ee.data.getFeatureViewTilesKey = function(params, opt_callback) {
const visualizationExpression = params.visParams ?
ee.data.expressionAugmenter_(
ee.Serializer.encodeCloudApiExpression(params.visParams)) :
null;
const map = new ee.api.FeatureView({
name: null,
asset: params.assetId,
visualizationExpression,
});
const fields = ['name'];
const call = new ee.apiclient.Call(opt_callback);
return call.handle(
call.featureView()
.create(call.projectsPath(), map, {fields})
.then((response) => {
const formatTileUrl = (x, y, z) =>
`${ee.apiclient.getTileBaseUrl()}/${ee.apiclient.VERSION}/${
response['name']}/tiles/${z}/${x}/${y}`;
const token = response['name'].split('/').pop();
return {
token,
formatTileUrl,
};
}));
};
/**
* List features for a given table asset.
* @param {string} asset The table asset ID to query.
* @param {!ee.api.ProjectsAssetsListFeaturesNamedParameters} params An object
* containing request parameters with the following possible values:
* <table>
* <tr>
* <td><code> pageSize </code> (number): An optional maximum number of
* results per page, default is 1000.</td>
* </tr>
* <tr>
* <td><code> pageToken </code> (string): An optional token identifying
* a page of results the server should return, usually taken from the
* response object.</td>
* </tr>
* <tr>
* <td><code> region </code> (string): If present, a geometry defining
* a query region, specified as a GeoJSON geometry
* string (see RFC 7946).</td>
* </tr>
* <tr>
* <td><code> filter </code> (comma-separated strings): If present,
* specifies additional simple property
* filters (see https://google.aip.dev/160).</td>
* </tr>
* </table>
* @param {function(?ee.api.ListFeaturesResponse, string=)=} opt_callback An
* optional callback, called with two parameters: the first is the resulting
* list of features and the second is an error string on failure. If not
* supplied, the call is made synchronously.
* @return {?ee.api.ListFeaturesResponse} The call results. Null if a
* callback is specified.
* @export
*/
ee.data.listFeatures = function(asset, params, opt_callback) {
const call = new ee.apiclient.Call(opt_callback);
const name = ee.rpc_convert.assetIdToAssetName(asset);
return call.handle(call.assets().listFeatures(name, params));
};
/**
* Sends a request to compute a value.
* @param {*} obj
* @param {function(*)=} opt_callback
* @return {!proto.google.protobuf.Value|!Object|null} result
* @export
*/
ee.data.computeValue = function(obj, opt_callback) {
const serializer = new ee.Serializer(true);
const expression = ee.Serializer.encodeCloudApiExpressionWithSerializer(
serializer, obj, /* unboundName= */ undefined);
let extraMetadata = {};
const request = {
expression: ee.data.expressionAugmenter_(expression, extraMetadata)
};
const workloadTag = ee.data.getWorkloadTag();
if (workloadTag) {
request.workloadTag = workloadTag;
}
const call = new ee.apiclient.Call(opt_callback);
return call.handle(
call.value()
.compute(call.projectsPath(), new ee.api.ComputeValueRequest(request))
.then(x => x['result']));
};
/**
* Get a Thumbnail Id for a given asset.
* @param {!ee.data.ThumbnailOptions} params An object containing thumbnail
* options with the following possible values:
* <table>
* <tr>
* <td><code> image </code> (ee.Image) The image to make a
* thumbnail.</td>
* </tr>
* <tr>
* <td><code> bands </code> (array of strings) An array of band
* names.</td>
* </tr>
* <tr>
* <td><code> format </code> (string) The file
* format ("png", "jpg", "geotiff").</td>
* </tr>
* <tr>
* <td><code> name </code> (string): The base name.</td>
* </tr>
* </table>
* Use ee.Image.getThumbURL for region, dimensions, and visualization
* options support.
* @param {function(?ee.data.ThumbnailId, string=)=} opt_callback
* An optional callback. If not supplied, the call is made synchronously.
* @return {?ee.data.ThumbnailId} The thumb ID and optional token, or null if a
* callback is specified.
* @export
*/
ee.data.getThumbId = function(params, opt_callback) {
// We only really support accessing this method via ee.Image.getThumbURL,
// which folds almost all the parameters into the Image itself.
if (typeof params.image === 'string') {
throw new Error('Image as JSON string not supported.');
}
if (params.version !== undefined) {
throw new Error('Image version specification not supported.');
}
if (params.region !== undefined) {
throw new Error(
'"region" not supported in call to ee.data.getThumbId. ' +
'Use ee.Image.getThumbURL.');
}
if (params.dimensions !== undefined) {
throw new Error(
'"dimensions" is not supported in call to ' +
'ee.data.getThumbId. Use ee.Image.getThumbURL.');
}
const thumbnail = new ee.api.Thumbnail({
name: null,
expression: ee.data.expressionAugmenter_(
ee.Serializer.encodeCloudApiExpression(params.image)),
fileFormat: ee.rpc_convert.fileFormat(params.format),
filenamePrefix: params.name,
bandIds: ee.rpc_convert.bandList(params.bands),
visualizationOptions: ee.rpc_convert.visualizationOptions(params),
grid: null,
});
const queryParams = {fields: 'name'};
const workloadTag = ee.data.getWorkloadTag();
if (workloadTag) {
queryParams.workloadTag = workloadTag;
}
const getResponse = (response) => {
/** @type {!ee.data.ThumbnailId} */
const ret = {thumbid: response['name'], token: ''};
return ret;
};
const call = new ee.apiclient.Call(opt_callback);
return call.handle(call.thumbnails()
.create(call.projectsPath(), thumbnail, queryParams)
.then(getResponse));
};
/**
* Get a Video Thumbnail Id for a given asset.
* @param {!ee.data.VideoThumbnailOptions} params Parameters to make the request
* with.
* @param {function(?ee.data.ThumbnailId, string=)=} opt_callback
* An optional callback. If not supplied, the call is made synchronously.
* @return {?ee.data.ThumbnailId} The thumb ID and optional token, or null if a
* callback is specified.
* @export
*/
ee.data.getVideoThumbId = function(params, opt_callback) {
const videoOptions = new ee.api.VideoOptions({
framesPerSecond: params.framesPerSecond || null,
maxFrames: params.maxFrames || null,
maxPixelsPerFrame: params.maxPixelsPerFrame || null,
});
const request = new ee.api.VideoThumbnail({
name: null,
expression: ee.data.expressionAugmenter_(
ee.Serializer.encodeCloudApiExpression(params.imageCollection)),
fileFormat: ee.rpc_convert.fileFormat(params.format),
videoOptions: videoOptions,
grid: null,
});
const queryParams = {fields: 'name'};
const workloadTag = ee.data.getWorkloadTag();
if (workloadTag) {
queryParams.workloadTag = workloadTag;
}
const getResponse = (response) => {
/** @type {!ee.data.ThumbnailId} */
const ret = {thumbid: response['name'], token: ''};
return ret;
};
const call = new ee.apiclient.Call(opt_callback);
return call.handle(call.videoThumbnails()
.create(call.projectsPath(), request, queryParams)
.then(getResponse));
};
/**
* Get a Filmstrip Thumbnail Id for a given asset.
* @param {!ee.data.FilmstripThumbnailOptions} params Parameters to make the
* request with.
* @param {function(?ee.data.ThumbnailId, string=)=} opt_callback
* An optional callback. If not supplied, the call is made synchronously.
* @return {?ee.data.ThumbnailId} The thumb ID and optional token, or null if a
* callback is specified.
* @export
*/
ee.data.getFilmstripThumbId = function(params, opt_callback) {
const request = new ee.api.FilmstripThumbnail({
name: null,
expression: ee.data.expressionAugmenter_(
ee.Serializer.encodeCloudApiExpression(params.imageCollection)),
fileFormat: ee.rpc_convert.fileFormat(params.format),
orientation: ee.rpc_convert.orientation(params.orientation),
grid: null,
});
const queryParams = {fields: 'name'};
const workloadTag = ee.data.getWorkloadTag();
if (workloadTag) {
queryParams.workloadTag = workloadTag;
}
const getResponse = (response) => {
/** @type {!ee.data.ThumbnailId} */
const ret = {thumbid: response['name'], token: ''};
return ret;
};
const call = new ee.apiclient.Call(opt_callback);
return call.handle(call.filmstripThumbnails()
.create(call.projectsPath(), request, queryParams)
.then(getResponse));
};
/**
* Create a thumbnail URL from a thumbid and token.
* @param {!ee.data.ThumbnailId} id A thumbnail ID and token.
* @return {string} The thumbnail URL.
* @export
*/
ee.data.makeThumbUrl = function(id) {
const base = ee.apiclient.getTileBaseUrl();
return `${base}/${ee.apiclient.VERSION}/${id.thumbid}:getPixels`;
};
/**
* Get a Download ID.
*
* @param {!Object} params An object containing download options with the
* following possible values:
* <table>
* <tr>
* <td><code> name: </code> a base name to use when constructing
* filenames. Only applicable when format is "ZIPPED_GEO_TIFF"
* (default), "ZIPPED_GEO_TIFF_PER_BAND", or filePerBand is true.
* Defaults to the image id (or "download" for computed images) when
* format is "ZIPPED_GEO_TIFF", "ZIPPED_GEO_TIFF_PER_BAND", or
* filePerBand is true, otherwise a random character string is
* generated. Band names are appended when filePerBand is true.</td>
* </tr>
* <tr>
* <td><code> bands: </code> a description of the bands to download. Must
* be an array of band names or an array of dictionaries, each with the
* following keys (optional parameters apply only when filePerBand is
* true):<ul style="list-style-type:none;">
* <li><code> id: </code> the name of the band, a string, required.
* <li><code> crs: </code> an optional CRS string defining the
* band projection.</li>
* <li><code> crs_transform: </code> an optional array of 6 numbers
* specifying an affine transform from the specified CRS, in
* row-major order: [xScale, xShearing, xTranslation, yShearing,
* yScale, yTranslation]</li>
* <li><code> dimensions: </code> an optional array of two integers
* defining the width and height to which the band is cropped.</li>
* <li><code> scale: </code> an optional number, specifying the scale
* in meters of the band; ignored if crs and crs_transform are
* specified.</li></ul></td>
* </tr>
* <tr>
* <td><code> crs: </code> a default CRS string to use for any bands that
* do not explicitly specify one.</td>
* </tr>
* <tr>
* <td><code> crs_transform: </code> a default affine transform to use for
* any bands that do not specify one, of the same format as the
* <code>crs_transform</code> of bands.</td>
* </tr>
* <tr>
* <td><code> dimensions: </code> default image cropping dimensions to use
* for any bands that do not specify them.</td>
* </tr>
* <tr>
* <td><code> scale: </code> a default scale to use for any bands that do
* not specify one; ignored if <code>crs</code> and
* <code>crs_transform</code> are specified.</td>
* </tr>
* <tr>
* <td><code> region: </code> a polygon specifying a region to download;
* ignored if <code>crs</code> and <code>crs_transform</code> is
* specified.</td>
* </tr>
* <tr>
* <td><code> filePerBand: </code> whether to produce a separate GeoTIFF
* per band (boolean). Defaults to true. If false, a single GeoTIFF is
* produced and all band-level transformations will be ignored. Note
* that this is ignored if the format is "ZIPPED_GEO_TIFF" or
* "ZIPPED_GEO_TIFF_PER_BAND".</td>
* </tr>
* <tr>
* <td><code> format: </code> the download format. One of:
* <ul>
* <li> "ZIPPED_GEO_TIFF" (GeoTIFF file wrapped in a zip file,
* default)</li>
* <li> "ZIPPED_GEO_TIFF_PER_BAND" (Multiple GeoTIFF files wrapped
* in a zip file)</li>
* <li> "NPY" (NumPy binary format)</li>
* </ul>
* If "GEO_TIFF" or "NPY", filePerBand and all band-level
* transformations will be ignored. Loading a NumPy output results in
* a structured array.</td>
* </tr>
* <tr>
* <td><code> id: </code> deprecated, use image parameter.</td>
* </table>
* @param {function(?ee.data.DownloadId, string=)=} opt_callback An optional
* callback. If not supplied, the call is made synchronously.
* @return {?ee.data.DownloadId} A download id and token, or null if a callback
* is specified.
* @export
*/
ee.data.getDownloadId = function(params, opt_callback) {
params = Object.assign({}, params);
// Previously, the docs required an image ID parameter that was changed
// to image, so we cast the ID to an ee.Image.
if (params['id']) {
// This resolves the circular dependency between data.js and image.js.
const eeImage = goog.module.get('ee.Image');
params['image'] = new eeImage(params['id']);
}
if (typeof params['image'] === 'string') {
throw new Error('Image as serialized JSON string not supported.');
}
if (!params['image']) {
throw new Error('Missing ID or image parameter.');
}
// The default is a zipped GeoTIFF per band if no format or filePerBand
// parameter is specified.
params['filePerBand'] = params['filePerBand'] !== false;
params['format'] = params['format'] ||
(params['filePerBand'] ? 'ZIPPED_GEO_TIFF_PER_BAND' : 'ZIPPED_GEO_TIFF');
if (params['region'] != null &&
(params['scale'] != null || params['crs_transform'] != null) &&
params['dimensions'] != null) {
throw new Error(
'Cannot specify (bounding region, crs_transform/scale, dimensions) ' +
'simultaneously.');
}
if (typeof params['bands'] === 'string') {
// Bands may be a stringified JSON string or a comma-separated string.
try {
params['bands'] = JSON.parse(params['bands']);
} catch (e) {
params['bands'] = ee.rpc_convert.bandList(params['bands']);
}
}
if (params['bands'] && !Array.isArray(params['bands'])) {
throw new Error('Bands parameter must be an array.');
}
if (params['bands'] &&
params['bands'].every((band) => typeof band === 'string')) {
// Support expressing the bands list as a list of strings.
params['bands'] = params['bands'].map((band) => {
return {id: band};
});
}
if (params['bands'] && params['bands'].some(({id}) => id == null)) {
throw new Error('Each band dictionary must have an id.');
}
if (typeof params['region'] === 'string') {
params['region'] = JSON.parse(params['region']);
}
if (typeof params['crs_transform'] === 'string') {
try {
// Try parsing the list as a JSON.
params['crs_transform'] = JSON.parse(params['crs_transform']);
} catch (e) {
} // Let the malformed string fall through.
}
const image = ee.data.images.buildDownloadIdImage(params['image'], params);
const thumbnail = new ee.api.Thumbnail({
name: null,
expression: ee.data.expressionAugmenter_(
ee.Serializer.encodeCloudApiExpression(image)),
fileFormat: ee.rpc_convert.fileFormat(params['format']),
filenamePrefix: params['name'],
bandIds: params['bands'] &&
ee.rpc_convert.bandList(params['bands'].map((band) => band.id)),
grid: null,
});
const queryParams = {fields: 'name'};
const workloadTag = ee.data.getWorkloadTag();
if (workloadTag) {
queryParams.workloadTag = workloadTag;
}
const getResponse = (response) => {
/** @type {!ee.data.DownloadId} */
const ret = {docid: response['name'], token: ''};
return ret;
};
const call = new ee.apiclient.Call(opt_callback);
return call.handle(call.thumbnails()
.create(call.projectsPath(), thumbnail, queryParams)
.then(getResponse));
};
/**
* Create a download URL from a docid and token.
*
* @param {!ee.data.DownloadId} id A download id and token.
* @return {string} The download URL.
* @export
*/
ee.data.makeDownloadUrl = function(id) {
ee.apiclient.initialize();
const base = ee.apiclient.getTileBaseUrl();
return `${base}/${ee.apiclient.VERSION}/${id.docid}:getPixels`;
};
/**
* Get a download ID.
* @param {!Object} params An object containing table download options with the
* following possible values:
* <table>
* <tr>
* <td><code> table: </code> The feature collection to download.</td>
* </tr>
* <tr>
* <td><code> format: </code> The download format, CSV, JSON, KML,
* KMZ or TF_RECORD.</td>
* </tr>
* <tr>
* <td><code> selectors: </code> List of strings of selectors that can
* be used to determine which attributes will be downloaded.</td>
* </tr>
* <tr>
* <td><code> filename: </code> The name of the file that will
* be downloaded.</td>
* </tr>
* </table>
* @param {function(?ee.data.DownloadId, string=)=} opt_callback An optional
* callback. If not supplied, the call is made synchronously.
* @return {?ee.data.DownloadId} A download id and token, or null if a
* callback is specified.
* @export
*/
ee.data.getTableDownloadId = function(params, opt_callback) {
const call = new ee.apiclient.Call(opt_callback);
const fileFormat = ee.rpc_convert.tableFileFormat(params['format']);
const expression = ee.data.expressionAugmenter_(
ee.Serializer.encodeCloudApiExpression(params['table']));
// Maybe convert selectors to an Array of strings.
// Previously a string with commas delimiting each selector was supported.
let selectors = null;
if (params['selectors'] != null) {
if (typeof params['selectors'] === 'string') {
selectors = params['selectors'].split(',');
} else if (
Array.isArray(params['selectors']) &&
params['selectors'].every((x) => typeof x === 'string')) {
selectors = params['selectors'];
} else {
throw new Error('\'selectors\' parameter must be an array of strings.');
}
}
const filename = params['filename'] || null;
const table = new ee.api.Table({
name: null,
expression,
fileFormat,
selectors,
filename,
});
const queryParams = {fields: 'name'};
const workloadTag = ee.data.getWorkloadTag();
if (workloadTag) {
queryParams.workloadTag = workloadTag;
}
/** @type {function(!ee.api.Table): !ee.data.DownloadId} */
const getResponse = (res) => {
/** @type {!ee.data.DownloadId} */
const ret = {docid: res.name || '', token: ''};
return ret;
};
return call.handle(call.tables()
.create(call.projectsPath(), table, queryParams)
.then(getResponse));
};
/**
* Create a table download URL from a docid and token.
* @param {!ee.data.DownloadId} id A table download id and token.