@maptiler/client 1.7.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/.github/pull_request_template.md +11 -0
  2. package/.github/workflows/format-lint.yml +24 -0
  3. package/CHANGELOG.md +25 -0
  4. package/dist/maptiler-client.cjs +388 -306
  5. package/dist/maptiler-client.cjs.map +1 -1
  6. package/dist/maptiler-client.d.ts +270 -100
  7. package/dist/maptiler-client.min.mjs +1 -1
  8. package/dist/maptiler-client.mjs +380 -294
  9. package/dist/maptiler-client.mjs.map +1 -1
  10. package/package.json +7 -5
  11. package/readme.md +133 -1
  12. package/rollup.config.js +3 -3
  13. package/dist/maptiler-client.umd.js +0 -1541
  14. package/dist/maptiler-client.umd.js.map +0 -1
  15. package/dist/maptiler-client.umd.min.js +0 -1
  16. package/examples/test-browser-es.html +0 -103
  17. package/examples/test-browser-umd.html +0 -90
  18. package/examples/test-node.js +0 -52
  19. package/src/callFetch.ts +0 -18
  20. package/src/config.ts +0 -68
  21. package/src/defaults.ts +0 -11
  22. package/src/demProfiler/getElevation.ts +0 -46
  23. package/src/demProfiler/index.ts +0 -240
  24. package/src/demProfiler/tileCover.ts +0 -96
  25. package/src/geometry/area.ts +0 -96
  26. package/src/geometry/distance.ts +0 -45
  27. package/src/geometry/index.ts +0 -3
  28. package/src/geometry/util.ts +0 -34
  29. package/src/index.ts +0 -114
  30. package/src/language.ts +0 -87
  31. package/src/mapstyle.ts +0 -968
  32. package/src/services/ServiceError.ts +0 -13
  33. package/src/services/coordinates.ts +0 -263
  34. package/src/services/data.ts +0 -63
  35. package/src/services/geocoding.ts +0 -461
  36. package/src/services/geolocation.ts +0 -139
  37. package/src/services/simplify.ts +0 -87
  38. package/src/services/staticMaps.ts +0 -463
@@ -1,1541 +0,0 @@
1
- (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.maptilerClient = {}));
5
- })(this, (function (exports) { 'use strict';
6
-
7
- function tryGettingFetch() {
8
- if (typeof self !== "undefined") {
9
- return fetch.bind(self);
10
- }
11
- if (typeof global !== "undefined" && global.fetch) {
12
- return global.fetch;
13
- }
14
- return null;
15
- }
16
- class ClientConfig {
17
- constructor() {
18
- /**
19
- * MapTiler Cloud API key
20
- */
21
- this._apiKey = "";
22
- /**
23
- * The fetch function. To be set if in Node < 18, otherwise
24
- * will be automatically resolved.
25
- */
26
- this._fetch = tryGettingFetch();
27
- }
28
- /**
29
- * Set the MapTiler Cloud API key
30
- */
31
- set apiKey(k) {
32
- this._apiKey = k;
33
- }
34
- /**
35
- * Get the MapTiler Cloud API key
36
- */
37
- get apiKey() {
38
- return this._apiKey;
39
- }
40
- /**
41
- * Set a the custom fetch function to replace the default one
42
- */
43
- set fetch(f) {
44
- this._fetch = f;
45
- }
46
- /**
47
- * Get the fetch fucntion
48
- */
49
- get fetch() {
50
- return this._fetch;
51
- }
52
- }
53
- const config = new ClientConfig();
54
-
55
- const LanguageGeocoding = {
56
- AUTO: "auto",
57
- ALBANIAN: "sq",
58
- ARABIC: "ar",
59
- ARMENIAN: "hy",
60
- AZERBAIJANI: "az",
61
- BELORUSSIAN: "be",
62
- BOSNIAN: "bs",
63
- BRETON: "br",
64
- BULGARIAN: "bg",
65
- CATALAN: "ca",
66
- CHINESE: "zh",
67
- CROATIAN: "hr",
68
- CZECH: "cs",
69
- DANISH: "da",
70
- DUTCH: "nl",
71
- ENGLISH: "en",
72
- ESPERANTO: "eo",
73
- ESTONIAN: "et",
74
- FINNISH: "fi",
75
- FRENCH: "fr",
76
- FRISIAN: "fy",
77
- GEORGIAN: "ka",
78
- GERMAN: "de",
79
- GREEK: "el",
80
- HEBREW: "he",
81
- HUNGARIAN: "hu",
82
- ICELANDIC: "is",
83
- IRISH: "ga",
84
- ITALIAN: "it",
85
- JAPANESE: "ja",
86
- KANNADA: "kn",
87
- KAZAKH: "kk",
88
- KOREAN: "ko",
89
- ROMAN_LATIN: "la",
90
- LATVIAN: "lv",
91
- LITHUANIAN: "lt",
92
- LUXEMBOURGISH: "lb",
93
- MACEDONIAN: "mk",
94
- MALTESE: "mt",
95
- NORWEGIAN: "no",
96
- POLISH: "pl",
97
- PORTUGUESE: "pt",
98
- ROMANIAN: "ro",
99
- ROMANSH: "rm",
100
- RUSSIAN: "ru",
101
- SCOTTISH_GAELIC: "gd",
102
- SERBIAN_CYRILLIC: "sr",
103
- SLOVAK: "sk",
104
- SLOVENE: "sl",
105
- SPANISH: "es",
106
- SWEDISH: "sv",
107
- THAI: "th",
108
- TURKISH: "tr",
109
- UKRAINIAN: "uk",
110
- WELSH: "cy"
111
- };
112
- const languageCodeSet = new Set(Object.values(LanguageGeocoding));
113
- function getAutoLanguageGeocoding() {
114
- if (typeof navigator === "undefined") {
115
- return Intl.DateTimeFormat().resolvedOptions().locale.split("-")[0];
116
- }
117
- const canditatelangs = Array.from(
118
- new Set(navigator.languages.map((l) => l.split("-")[0]))
119
- ).filter((l) => languageCodeSet.has(l));
120
- return canditatelangs.length ? canditatelangs[0] : LanguageGeocoding.ENGLISH;
121
- }
122
-
123
- async function callFetch(resource, options = {}) {
124
- if (config.fetch === null) {
125
- throw new Error(
126
- "The fetch function was not found. If on NodeJS < 18 please specify the fetch function with config.fetch"
127
- );
128
- }
129
- if (new URL(resource).searchParams.get("key").trim() === "") {
130
- throw new Error(
131
- "The MapTiler Cloud API key is missing. Set it in `config.apiKey` or get one for free at https://maptiler.com"
132
- );
133
- }
134
- return config.fetch(resource, options);
135
- }
136
-
137
- const defaults = {
138
- maptilerApiURL: "https://api.maptiler.com/",
139
- mapStyle: "streets-v2"
140
- };
141
- Object.freeze(defaults);
142
-
143
- class ServiceError extends Error {
144
- constructor(res, customMessage = "") {
145
- super(
146
- `Call to enpoint ${res.url} failed with the status code ${res.status}. ${customMessage}`
147
- );
148
- this.res = res;
149
- }
150
- }
151
-
152
- const customMessages$3 = {
153
- 400: "Query too long / Invalid parameters",
154
- 403: "Key is missing, invalid or restricted"
155
- };
156
- function addLanguageGeocodingOptions(searchParams, options) {
157
- if (options.language == void 0) {
158
- return;
159
- }
160
- const languages = Array.from(
161
- new Set(
162
- (Array.isArray(options.language) ? options.language : [options.language]).map(
163
- (lang) => lang === LanguageGeocoding.AUTO ? getAutoLanguageGeocoding() : lang
164
- )
165
- )
166
- ).join(",");
167
- searchParams.set("language", languages);
168
- }
169
- function addCommonForwardAndReverseGeocodingOptions(searchParams, options) {
170
- searchParams.set("key", options.apiKey ?? config.apiKey);
171
- if (options.limit != void 0) {
172
- searchParams.set("limit", String(options.limit));
173
- }
174
- if (options.types != void 0) {
175
- searchParams.set("types", options.types.join(","));
176
- }
177
- addLanguageGeocodingOptions(searchParams, options);
178
- }
179
- function addForwardGeocodingOptions(searchParams, options) {
180
- addCommonForwardAndReverseGeocodingOptions(searchParams, options);
181
- if (options.bbox != void 0) {
182
- searchParams.set("bbox", options.bbox.join(","));
183
- }
184
- if (options.proximity != void 0) {
185
- searchParams.set("proximity", options.proximity.join(","));
186
- }
187
- if (options.country != void 0) {
188
- searchParams.set("country", options.country.join(","));
189
- }
190
- if (options.fuzzyMatch != void 0) {
191
- searchParams.set("fuzzyMatch", options.fuzzyMatch ? "true" : "false");
192
- }
193
- if (options.autocomplete != void 0) {
194
- searchParams.set("autocomplete", options.autocomplete ? "true" : "false");
195
- }
196
- }
197
- async function forward(query, options = {}) {
198
- if (typeof query !== "string" || query.trim().length === 0) {
199
- throw new Error("The query must be a non-empty string");
200
- }
201
- const endpoint = new URL(
202
- `geocoding/${encodeURIComponent(query)}.json`,
203
- defaults.maptilerApiURL
204
- );
205
- const { searchParams } = endpoint;
206
- addForwardGeocodingOptions(searchParams, options);
207
- const urlWithParams = endpoint.toString();
208
- const res = await callFetch(urlWithParams);
209
- if (!res.ok) {
210
- throw new ServiceError(res, customMessages$3[res.status] ?? "");
211
- }
212
- const obj = await res.json();
213
- return obj;
214
- }
215
- async function reverse(position, options = {}) {
216
- if (!Array.isArray(position) || position.length < 2) {
217
- throw new Error("The position must be an array of form [lng, lat].");
218
- }
219
- const endpoint = new URL(
220
- `geocoding/${position[0]},${position[1]}.json`,
221
- defaults.maptilerApiURL
222
- );
223
- addCommonForwardAndReverseGeocodingOptions(endpoint.searchParams, options);
224
- const urlWithParams = endpoint.toString();
225
- const res = await callFetch(urlWithParams);
226
- if (!res.ok) {
227
- throw new ServiceError(res, customMessages$3[res.status] ?? "");
228
- }
229
- const obj = await res.json();
230
- return obj;
231
- }
232
- async function byId(id, options = {}) {
233
- const endpoint = new URL(`geocoding/${id}.json`, defaults.maptilerApiURL);
234
- endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
235
- addLanguageGeocodingOptions(endpoint.searchParams, options);
236
- const urlWithParams = endpoint.toString();
237
- const res = await callFetch(urlWithParams);
238
- if (!res.ok) {
239
- throw new ServiceError(res, customMessages$3[res.status] ?? "");
240
- }
241
- const obj = await res.json();
242
- return obj;
243
- }
244
- async function batch(queries, options = {}) {
245
- if (!queries.length) {
246
- return [];
247
- }
248
- const joinedQuery = queries.map((query) => encodeURIComponent(query)).join(";");
249
- const endpoint = new URL(
250
- `geocoding/${joinedQuery}.json`,
251
- defaults.maptilerApiURL
252
- );
253
- const { searchParams } = endpoint;
254
- addForwardGeocodingOptions(searchParams, options);
255
- const urlWithParams = endpoint.toString();
256
- const res = await callFetch(urlWithParams);
257
- if (!res.ok) {
258
- throw new ServiceError(res, customMessages$3[res.status] ?? "");
259
- }
260
- const obj = await res.json();
261
- return queries.length === 1 ? [obj] : obj;
262
- }
263
- const geocoding = {
264
- forward,
265
- reverse,
266
- byId,
267
- batch,
268
- language: LanguageGeocoding
269
- };
270
-
271
- const customMessages$2 = {
272
- 403: "Key is missing, invalid or restricted"
273
- };
274
- async function info(options = {}) {
275
- const endpoint = new URL(`geolocation/ip.json`, defaults.maptilerApiURL);
276
- endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
277
- const urlWithParams = endpoint.toString();
278
- const res = await callFetch(urlWithParams);
279
- if (!res.ok) {
280
- throw new ServiceError(
281
- res,
282
- res.status in customMessages$2 ? customMessages$2[res.status] : ""
283
- );
284
- }
285
- const obj = await res.json();
286
- return obj;
287
- }
288
- const geolocation = {
289
- info
290
- };
291
-
292
- const customMessages$1 = {
293
- 403: "Key is missing, invalid or restricted"
294
- };
295
- async function search(query, options = {}) {
296
- if (typeof query !== "string" || query.trim().length === 0) {
297
- throw new Error("The query must be a non-empty string");
298
- }
299
- const endpoint = new URL(
300
- `coordinates/search/${query}.json`,
301
- defaults.maptilerApiURL
302
- );
303
- endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
304
- if ("limit" in options) {
305
- endpoint.searchParams.set("limit", options.limit.toString());
306
- }
307
- if ("transformations" in options) {
308
- endpoint.searchParams.set(
309
- "transformations",
310
- options.transformations.toString()
311
- );
312
- }
313
- if ("exports" in options) {
314
- endpoint.searchParams.set("exports", options.exports.toString());
315
- }
316
- const urlWithParams = endpoint.toString();
317
- const res = await callFetch(urlWithParams);
318
- if (!res.ok) {
319
- throw new ServiceError(
320
- res,
321
- res.status in customMessages$1 ? customMessages$1[res.status] : ""
322
- );
323
- }
324
- const obj = await res.json();
325
- return obj;
326
- }
327
- async function transform(positions, options = {}) {
328
- const coordinatesStr = (Array.isArray(positions[0]) ? positions : [positions]).map((coord) => `${coord[0]},${coord[1]}`).join(";");
329
- const endpoint = new URL(
330
- `coordinates/transform/${coordinatesStr}.json`,
331
- defaults.maptilerApiURL
332
- );
333
- endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
334
- if ("sourceCrs" in options) {
335
- endpoint.searchParams.set("s_srs", options.sourceCrs.toString());
336
- }
337
- if ("targetCrs" in options) {
338
- endpoint.searchParams.set("t_srs", options.targetCrs.toString());
339
- }
340
- if ("operations" in options) {
341
- endpoint.searchParams.set(
342
- "ops",
343
- (Array.isArray(options.operations) ? options.operations : [options.operations]).join("|")
344
- );
345
- }
346
- const urlWithParams = endpoint.toString();
347
- const res = await callFetch(urlWithParams);
348
- if (!res.ok) {
349
- throw new ServiceError(
350
- res,
351
- res.status in customMessages$1 ? customMessages$1[res.status] : ""
352
- );
353
- }
354
- const obj = await res.json();
355
- return obj;
356
- }
357
- const coordinates = {
358
- search,
359
- transform
360
- };
361
-
362
- const customMessages = {
363
- 403: "Key is missing, invalid or restricted"
364
- };
365
- async function get(dataId, options = {}) {
366
- if (typeof dataId !== "string" || dataId.trim().length === 0) {
367
- throw new Error("The data ID must be a non-empty string");
368
- }
369
- const endpoint = new URL(
370
- `data/${encodeURIComponent(dataId)}/features.json`,
371
- defaults.maptilerApiURL
372
- );
373
- endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
374
- const urlWithParams = endpoint.toString();
375
- const res = await callFetch(urlWithParams);
376
- if (!res.ok) {
377
- throw new ServiceError(
378
- res,
379
- res.status in customMessages ? customMessages[res.status] : ""
380
- );
381
- }
382
- const obj = await res.json();
383
- return obj;
384
- }
385
- const data = {
386
- get
387
- };
388
-
389
- function expandMapStyle(style) {
390
- const maptilerDomainRegex = /^maptiler:\/\/(.*)/;
391
- let match;
392
- const trimmed = style.trim();
393
- let expandedStyle;
394
- if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
395
- expandedStyle = trimmed;
396
- } else if ((match = maptilerDomainRegex.exec(trimmed)) !== null) {
397
- expandedStyle = `https://api.maptiler.com/maps/${match[1]}/style.json`;
398
- } else {
399
- expandedStyle = `https://api.maptiler.com/maps/${trimmed}/style.json`;
400
- }
401
- return expandedStyle;
402
- }
403
- class MapStyleVariant {
404
- constructor(name, variantType, id, referenceStyle, description, imageURL) {
405
- this.name = name;
406
- this.variantType = variantType;
407
- this.id = id;
408
- this.referenceStyle = referenceStyle;
409
- this.description = description;
410
- this.imageURL = imageURL;
411
- }
412
- /**
413
- * Get the human-friendly name
414
- * @returns
415
- */
416
- getName() {
417
- return this.name;
418
- }
419
- getFullName() {
420
- return `${this.referenceStyle.getName()} ${this.name}`;
421
- }
422
- /**
423
- * Get the variant type (eg. "DEFAULT", "DARK", "PASTEL", etc.)
424
- * @returns
425
- */
426
- getType() {
427
- return this.variantType;
428
- }
429
- /**
430
- * Get the MapTiler Cloud id
431
- * @returns
432
- */
433
- getId() {
434
- return this.id;
435
- }
436
- /**
437
- * Get the human-friendly description
438
- */
439
- getDescription() {
440
- return this.description;
441
- }
442
- /**
443
- * Get the reference style this variant belongs to
444
- * @returns
445
- */
446
- getReferenceStyle() {
447
- return this.referenceStyle;
448
- }
449
- /**
450
- * Check if a variant of a given type exists for _this_ variants
451
- * (eg. if this is a "DARK", then we can check if there is a "LIGHT" variant of it)
452
- * @param variantType
453
- * @returns
454
- */
455
- hasVariant(variantType) {
456
- return this.referenceStyle.hasVariant(variantType);
457
- }
458
- /**
459
- * Retrieve the variant of a given type. If not found, will return the "DEFAULT" variant.
460
- * (eg. _this_ "DARK" variant does not have any "PASTEL" variant, then the "DEFAULT" is returned)
461
- * @param variantType
462
- * @returns
463
- */
464
- getVariant(variantType) {
465
- return this.referenceStyle.getVariant(variantType);
466
- }
467
- /**
468
- * Get all the variants for _this_ variants, except _this_ current one
469
- * @returns
470
- */
471
- getVariants() {
472
- return this.referenceStyle.getVariants().filter((v) => v !== this);
473
- }
474
- /**
475
- * Get the image URL that represent _this_ variant
476
- * @returns
477
- */
478
- getImageURL() {
479
- return this.imageURL;
480
- }
481
- /**
482
- * Get the style as usable by MapLibre, a string (URL) or a plain style description (StyleSpecification)
483
- * @returns
484
- */
485
- getExpandedStyleURL() {
486
- return expandMapStyle(this.getId());
487
- }
488
- }
489
- class ReferenceMapStyle {
490
- constructor(name, id) {
491
- this.name = name;
492
- this.id = id;
493
- /**
494
- * Variants that belong to this reference style, key being the reference type
495
- */
496
- this.variants = {};
497
- /**
498
- * Variants that belong to this reference style, ordered by relevance
499
- */
500
- this.orderedVariants = [];
501
- }
502
- /**
503
- * Get the human-friendly name of this reference style
504
- * @returns
505
- */
506
- getName() {
507
- return this.name;
508
- }
509
- /**
510
- * Get the id of _this_ reference style
511
- * @returns
512
- */
513
- getId() {
514
- return this.id;
515
- }
516
- /**
517
- * Add a variant to _this_ reference style
518
- * @param v
519
- */
520
- addVariant(v) {
521
- this.variants[v.getType()] = v;
522
- this.orderedVariants.push(v);
523
- }
524
- /**
525
- * Check if a given variant type exists for this reference style
526
- * @param variantType
527
- * @returns
528
- */
529
- hasVariant(variantType) {
530
- return variantType in this.variants;
531
- }
532
- /**
533
- * Get a given variant. If the given type of variant does not exist for this reference style,
534
- * then the most relevant default variant is returned instead
535
- * @param variantType
536
- * @returns
537
- */
538
- getVariant(variantType) {
539
- return variantType in this.variants ? this.variants[variantType] : this.orderedVariants[0];
540
- }
541
- /**
542
- * Get the list of variants for this reference style
543
- * @returns
544
- */
545
- getVariants() {
546
- return Object.values(this.variants);
547
- }
548
- /**
549
- * Get the defualt variant for this reference style
550
- * @returns
551
- */
552
- getDefaultVariant() {
553
- return this.orderedVariants[0];
554
- }
555
- }
556
- const mapStylePresetList = [
557
- {
558
- referenceStyleID: "STREETS",
559
- name: "Streets",
560
- description: "",
561
- variants: [
562
- {
563
- id: "streets-v2",
564
- name: "Default",
565
- variantType: "DEFAULT",
566
- description: "",
567
- imageURL: ""
568
- },
569
- {
570
- id: "streets-v2-dark",
571
- name: "Dark",
572
- variantType: "DARK",
573
- description: "",
574
- imageURL: ""
575
- },
576
- {
577
- id: "streets-v2-light",
578
- name: "Light",
579
- variantType: "LIGHT",
580
- description: "",
581
- imageURL: ""
582
- },
583
- {
584
- id: "streets-v2-night",
585
- name: "Night",
586
- variantType: "NIGHT",
587
- description: "",
588
- imageURL: ""
589
- },
590
- {
591
- id: "streets-v2-pastel",
592
- name: "Pastel",
593
- variantType: "PASTEL",
594
- description: "",
595
- imageURL: ""
596
- }
597
- ]
598
- },
599
- {
600
- referenceStyleID: "OUTDOOR",
601
- name: "Outdoor",
602
- description: "",
603
- variants: [
604
- {
605
- id: "outdoor-v2",
606
- name: "Default",
607
- variantType: "DEFAULT",
608
- description: "",
609
- imageURL: ""
610
- },
611
- {
612
- id: "outdoor-v2-dark",
613
- name: "Dark",
614
- variantType: "DARK",
615
- description: "",
616
- imageURL: ""
617
- }
618
- ]
619
- },
620
- {
621
- referenceStyleID: "WINTER",
622
- name: "Winter",
623
- description: "",
624
- variants: [
625
- {
626
- id: "winter-v2",
627
- name: "Default",
628
- variantType: "DEFAULT",
629
- description: "",
630
- imageURL: ""
631
- },
632
- {
633
- id: "winter-v2-dark",
634
- name: "Dark",
635
- variantType: "DARK",
636
- description: "",
637
- imageURL: ""
638
- }
639
- ]
640
- },
641
- {
642
- referenceStyleID: "SATELLITE",
643
- name: "Satellite",
644
- description: "",
645
- variants: [
646
- {
647
- id: "satellite",
648
- name: "Default",
649
- variantType: "DEFAULT",
650
- description: "",
651
- imageURL: ""
652
- }
653
- ]
654
- },
655
- {
656
- referenceStyleID: "HYBRID",
657
- name: "Hybrid",
658
- description: "",
659
- variants: [
660
- {
661
- id: "hybrid",
662
- name: "Default",
663
- variantType: "DEFAULT",
664
- description: "",
665
- imageURL: ""
666
- }
667
- ]
668
- },
669
- {
670
- referenceStyleID: "BASIC",
671
- name: "Basic",
672
- description: "",
673
- variants: [
674
- {
675
- id: "basic-v2",
676
- name: "Default",
677
- variantType: "DEFAULT",
678
- description: "",
679
- imageURL: ""
680
- },
681
- {
682
- id: "basic-v2-dark",
683
- name: "Dark",
684
- variantType: "DARK",
685
- description: "",
686
- imageURL: ""
687
- },
688
- {
689
- id: "basic-v2-light",
690
- name: "Light",
691
- variantType: "LIGHT",
692
- description: "",
693
- imageURL: ""
694
- }
695
- ]
696
- },
697
- {
698
- referenceStyleID: "BRIGHT",
699
- name: "Bright",
700
- description: "",
701
- variants: [
702
- {
703
- id: "bright-v2",
704
- name: "Default",
705
- variantType: "DEFAULT",
706
- description: "",
707
- imageURL: ""
708
- },
709
- {
710
- id: "bright-v2-dark",
711
- name: "Dark",
712
- variantType: "DARK",
713
- description: "",
714
- imageURL: ""
715
- },
716
- {
717
- id: "bright-v2-light",
718
- name: "Light",
719
- variantType: "LIGHT",
720
- description: "",
721
- imageURL: ""
722
- },
723
- {
724
- id: "bright-v2-pastel",
725
- name: "Pastel",
726
- variantType: "PASTEL",
727
- description: "",
728
- imageURL: ""
729
- }
730
- ]
731
- },
732
- {
733
- referenceStyleID: "OPENSTREETMAP",
734
- name: "OpenStreetMap",
735
- description: "",
736
- variants: [
737
- {
738
- id: "openstreetmap",
739
- name: "Default",
740
- variantType: "DEFAULT",
741
- description: "",
742
- imageURL: ""
743
- }
744
- ]
745
- },
746
- {
747
- referenceStyleID: "TOPO",
748
- name: "Topo",
749
- description: "",
750
- variants: [
751
- {
752
- id: "topo-v2",
753
- name: "Default",
754
- variantType: "DEFAULT",
755
- description: "",
756
- imageURL: ""
757
- },
758
- {
759
- id: "topo-v2-dark",
760
- name: "Dark",
761
- variantType: "DARK",
762
- description: "",
763
- imageURL: ""
764
- },
765
- {
766
- id: "topo-v2-shiny",
767
- name: "Shiny",
768
- variantType: "SHINY",
769
- description: "",
770
- imageURL: ""
771
- },
772
- {
773
- id: "topo-v2-pastel",
774
- name: "Pastel",
775
- variantType: "PASTEL",
776
- description: "",
777
- imageURL: ""
778
- },
779
- {
780
- id: "topo-v2-topographique",
781
- name: "Topographique",
782
- variantType: "TOPOGRAPHIQUE",
783
- description: "",
784
- imageURL: ""
785
- }
786
- ]
787
- },
788
- {
789
- referenceStyleID: "VOYAGER",
790
- name: "Voyager",
791
- description: "",
792
- variants: [
793
- {
794
- id: "voyager-v2",
795
- name: "Default",
796
- variantType: "DEFAULT",
797
- description: "",
798
- imageURL: ""
799
- },
800
- {
801
- id: "voyager-v2-darkmatter",
802
- name: "Darkmatter",
803
- variantType: "DARK",
804
- description: "",
805
- imageURL: ""
806
- },
807
- {
808
- id: "voyager-v2-positron",
809
- name: "Positron",
810
- variantType: "LIGHT",
811
- description: "",
812
- imageURL: ""
813
- },
814
- {
815
- id: "voyager-v2-vintage",
816
- name: "Vintage",
817
- variantType: "VINTAGE",
818
- description: "",
819
- imageURL: ""
820
- }
821
- ]
822
- },
823
- {
824
- referenceStyleID: "TONER",
825
- name: "Toner",
826
- description: "",
827
- variants: [
828
- {
829
- id: "toner-v2",
830
- name: "Default",
831
- variantType: "DEFAULT",
832
- description: "",
833
- imageURL: ""
834
- },
835
- {
836
- id: "toner-v2-background",
837
- name: "Background",
838
- variantType: "BACKGROUND",
839
- description: "",
840
- imageURL: ""
841
- },
842
- {
843
- id: "toner-v2-lite",
844
- name: "Lite",
845
- variantType: "LITE",
846
- description: "",
847
- imageURL: ""
848
- },
849
- {
850
- id: "toner-v2-lines",
851
- name: "Lines",
852
- variantType: "LINES",
853
- description: "",
854
- imageURL: ""
855
- }
856
- ]
857
- },
858
- {
859
- referenceStyleID: "DATAVIZ",
860
- name: "Dataviz",
861
- description: "",
862
- variants: [
863
- {
864
- id: "dataviz",
865
- name: "Default",
866
- variantType: "DEFAULT",
867
- description: "",
868
- imageURL: ""
869
- },
870
- {
871
- id: "dataviz-dark",
872
- name: "Dark",
873
- variantType: "DARK",
874
- description: "",
875
- imageURL: ""
876
- },
877
- {
878
- id: "dataviz-light",
879
- name: "Light",
880
- variantType: "LIGHT",
881
- description: "",
882
- imageURL: ""
883
- }
884
- ]
885
- },
886
- {
887
- referenceStyleID: "BACKDROP",
888
- name: "Backdrop",
889
- description: "",
890
- variants: [
891
- {
892
- id: "backdrop",
893
- name: "Default",
894
- variantType: "DEFAULT",
895
- description: "",
896
- imageURL: ""
897
- },
898
- {
899
- id: "backdrop-dark",
900
- name: "Dark",
901
- variantType: "DARK",
902
- description: "",
903
- imageURL: ""
904
- },
905
- {
906
- id: "backdrop-light",
907
- name: "Light",
908
- variantType: "LIGHT",
909
- description: "",
910
- imageURL: ""
911
- }
912
- ]
913
- },
914
- {
915
- referenceStyleID: "OCEAN",
916
- name: "Ocean",
917
- description: "",
918
- variants: [
919
- {
920
- id: "ocean",
921
- name: "Default",
922
- variantType: "DEFAULT",
923
- description: "",
924
- imageURL: ""
925
- }
926
- ]
927
- }
928
- ];
929
- function makeReferenceStyleProxy(referenceStyle) {
930
- return new Proxy(referenceStyle, {
931
- get(target, prop, receiver) {
932
- if (target.hasVariant(prop)) {
933
- return target.getVariant(prop);
934
- }
935
- if (prop.toString().toUpperCase() === prop) {
936
- return referenceStyle.getDefaultVariant();
937
- }
938
- return Reflect.get(target, prop, receiver);
939
- }
940
- });
941
- }
942
- function buildMapStyles() {
943
- const mapStyle = {};
944
- for (let i = 0; i < mapStylePresetList.length; i += 1) {
945
- const refStyleInfo = mapStylePresetList[i];
946
- const refStyle = makeReferenceStyleProxy(
947
- new ReferenceMapStyle(refStyleInfo.name, refStyleInfo.referenceStyleID)
948
- );
949
- for (let j = 0; j < refStyleInfo.variants.length; j += 1) {
950
- const variantInfo = refStyleInfo.variants[j];
951
- const variant = new MapStyleVariant(
952
- variantInfo.name,
953
- // name
954
- variantInfo.variantType,
955
- // variantType
956
- variantInfo.id,
957
- // id
958
- refStyle,
959
- // referenceStyle
960
- variantInfo.description,
961
- variantInfo.imageURL
962
- // imageURL
963
- );
964
- refStyle.addVariant(variant);
965
- }
966
- mapStyle[refStyleInfo.referenceStyleID] = refStyle;
967
- }
968
- return mapStyle;
969
- }
970
- function styleToStyle(style) {
971
- if (!style) {
972
- return MapStyle[mapStylePresetList[0].referenceStyleID].getDefaultVariant().getId();
973
- }
974
- if (typeof style === "string" || style instanceof String) {
975
- return style.trim().toLowerCase();
976
- }
977
- if (style instanceof MapStyleVariant) {
978
- return style.getId();
979
- }
980
- if (style instanceof ReferenceMapStyle) {
981
- return style.getDefaultVariant().getId();
982
- }
983
- }
984
- const MapStyle = buildMapStyles();
985
-
986
- function getSqSegDist(p, p1, p2) {
987
- let x = p1[0], y = p1[1], dx = p2[0] - x, dy = p2[1] - y;
988
- if (dx !== 0 || dy !== 0) {
989
- const t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy);
990
- if (t > 1) {
991
- x = p2[0];
992
- y = p2[1];
993
- } else if (t > 0) {
994
- x += dx * t;
995
- y += dy * t;
996
- }
997
- }
998
- dx = p[0] - x;
999
- dy = p[1] - y;
1000
- return dx * dx + dy * dy;
1001
- }
1002
- function simplifyDPStep(points, first, last, sqTolerance, simplified) {
1003
- let maxSqDist = sqTolerance, index;
1004
- for (let i = first + 1; i < last; i++) {
1005
- const sqDist = getSqSegDist(points[i], points[first], points[last]);
1006
- if (sqDist > maxSqDist) {
1007
- index = i;
1008
- maxSqDist = sqDist;
1009
- }
1010
- }
1011
- if (maxSqDist > sqTolerance) {
1012
- if (index - first > 1) {
1013
- simplifyDPStep(points, first, index, sqTolerance, simplified);
1014
- }
1015
- simplified.push(points[index]);
1016
- if (last - index > 1) {
1017
- simplifyDPStep(points, index, last, sqTolerance, simplified);
1018
- }
1019
- }
1020
- }
1021
- function simplifyDouglasPeucker(points, sqTolerance) {
1022
- const last = points.length - 1;
1023
- const simplified = [points[0]];
1024
- simplifyDPStep(points, 0, last, sqTolerance, simplified);
1025
- simplified.push(points[last]);
1026
- return simplified;
1027
- }
1028
- function simplify(points, tolerance) {
1029
- if (points.length <= 2) {
1030
- return points;
1031
- }
1032
- const sqTolerance = tolerance !== void 0 ? tolerance * tolerance : 1;
1033
- const simplePoints = simplifyDouglasPeucker(points, sqTolerance);
1034
- return simplePoints;
1035
- }
1036
-
1037
- function staticMapMarkerToString(marker, includeColor = true) {
1038
- let str = `${marker[0]},${marker[1]}`;
1039
- if (marker.length === 3 && includeColor) {
1040
- str += `,${marker[2]}`;
1041
- }
1042
- return str;
1043
- }
1044
- function simplifyAndStringify(path, maxNbChar = 3e3) {
1045
- let str = path.map((point) => point.join(",")).join("|");
1046
- let tolerance = 5e-6;
1047
- const toleranceStep = 1e-5;
1048
- while (str.length > maxNbChar) {
1049
- const simplerPath = simplify(path, tolerance);
1050
- str = simplerPath.map((point) => `${point[0]},${point[1]}`).join("|");
1051
- tolerance += toleranceStep;
1052
- }
1053
- return str;
1054
- }
1055
- function centered(center, zoom, options = {}) {
1056
- const style = styleToStyle(options.style);
1057
- const scale = options.hiDPI ? "@2x" : "";
1058
- const format = options.format ?? "png";
1059
- let width = ~~(options.width ?? 1024);
1060
- let height = ~~(options.height ?? 1024);
1061
- if (options.hiDPI) {
1062
- width = ~~(width / 2);
1063
- height = ~~(height / 2);
1064
- }
1065
- const endpoint = new URL(
1066
- `maps/${encodeURIComponent(style)}/static/${center[0]},${center[1]},${zoom}/${width}x${height}${scale}.${format}`,
1067
- defaults.maptilerApiURL
1068
- );
1069
- if ("attribution" in options) {
1070
- endpoint.searchParams.set("attribution", options.attribution.toString());
1071
- }
1072
- if ("markers" in options) {
1073
- let markerStr = "";
1074
- const hasIcon = "markerIcon" in options;
1075
- if (hasIcon) {
1076
- markerStr += `icon:${options.markerIcon}|`;
1077
- }
1078
- if (hasIcon && "markerAnchor" in options) {
1079
- markerStr += `anchor:${options.markerAnchor}|`;
1080
- }
1081
- if (hasIcon && options.hiDPI) {
1082
- markerStr += `scale:2|`;
1083
- }
1084
- const markerList = Array.isArray(options.markers[0]) ? options.markers : [options.markers];
1085
- markerStr += markerList.map((m) => staticMapMarkerToString(m, !hasIcon)).join("|");
1086
- endpoint.searchParams.set("markers", markerStr);
1087
- }
1088
- if ("path" in options) {
1089
- let pathStr = "";
1090
- pathStr += `fill:${options.pathFillColor ?? "none"}|`;
1091
- if ("pathStrokeColor" in options) {
1092
- pathStr += `stroke:${options.pathStrokeColor}|`;
1093
- }
1094
- if ("pathWidth" in options) {
1095
- const pathWidth = options.pathWidth / (options.hiDPI ? 2 : 1);
1096
- pathStr += `width:${pathWidth.toString()}|`;
1097
- }
1098
- pathStr += simplifyAndStringify(options.path);
1099
- endpoint.searchParams.set("path", pathStr);
1100
- }
1101
- endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
1102
- return endpoint.toString();
1103
- }
1104
- function bounded(boundingBox, options = {}) {
1105
- const style = styleToStyle(options.style);
1106
- const scale = options.hiDPI ? "@2x" : "";
1107
- const format = options.format ?? "png";
1108
- let width = ~~(options.width ?? 1024);
1109
- let height = ~~(options.height ?? 1024);
1110
- if (options.hiDPI) {
1111
- width = ~~(width / 2);
1112
- height = ~~(height / 2);
1113
- }
1114
- const endpoint = new URL(
1115
- `maps/${encodeURIComponent(style)}/static/${boundingBox[0]},${boundingBox[1]},${boundingBox[2]},${boundingBox[3]}/${width}x${height}${scale}.${format}`,
1116
- defaults.maptilerApiURL
1117
- );
1118
- if ("attribution" in options) {
1119
- endpoint.searchParams.set("attribution", options.attribution.toString());
1120
- }
1121
- if ("padding" in options) {
1122
- endpoint.searchParams.set("padding", options.padding.toString());
1123
- }
1124
- if ("markers" in options) {
1125
- let markerStr = "";
1126
- const hasIcon = "markerIcon" in options;
1127
- if (hasIcon) {
1128
- markerStr += `icon:${options.markerIcon}|`;
1129
- }
1130
- if (hasIcon && "markerAnchor" in options) {
1131
- markerStr += `anchor:${options.markerAnchor}|`;
1132
- }
1133
- if (hasIcon && options.hiDPI) {
1134
- markerStr += `scale:2|`;
1135
- }
1136
- const markerList = Array.isArray(options.markers[0]) ? options.markers : [options.markers];
1137
- markerStr += markerList.map((m) => staticMapMarkerToString(m, !hasIcon)).join("|");
1138
- endpoint.searchParams.set("markers", markerStr);
1139
- }
1140
- if ("path" in options) {
1141
- let pathStr = "";
1142
- pathStr += `fill:${options.pathFillColor ?? "none"}|`;
1143
- if ("pathStrokeColor" in options) {
1144
- pathStr += `stroke:${options.pathStrokeColor}|`;
1145
- }
1146
- if ("pathWidth" in options) {
1147
- const pathWidth = options.pathWidth / (options.hiDPI ? 2 : 1);
1148
- pathStr += `width:${pathWidth.toString()}|`;
1149
- }
1150
- pathStr += simplifyAndStringify(options.path);
1151
- endpoint.searchParams.set("path", pathStr);
1152
- }
1153
- endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
1154
- return endpoint.toString();
1155
- }
1156
- function automatic(options = {}) {
1157
- if (!("markers" in options) && !("path" in options)) {
1158
- throw new Error(
1159
- "Automatic static maps require markers and/or path to be created."
1160
- );
1161
- }
1162
- const style = styleToStyle(options.style);
1163
- const scale = options.hiDPI ? "@2x" : "";
1164
- const format = options.format ?? "png";
1165
- let width = ~~(options.width ?? 1024);
1166
- let height = ~~(options.height ?? 1024);
1167
- if (options.hiDPI) {
1168
- width = ~~(width / 2);
1169
- height = ~~(height / 2);
1170
- }
1171
- const endpoint = new URL(
1172
- `maps/${encodeURIComponent(
1173
- style
1174
- )}/static/auto/${width}x${height}${scale}.${format}`,
1175
- defaults.maptilerApiURL
1176
- );
1177
- if ("attribution" in options) {
1178
- endpoint.searchParams.set("attribution", options.attribution.toString());
1179
- }
1180
- if ("padding" in options) {
1181
- endpoint.searchParams.set("padding", options.padding.toString());
1182
- }
1183
- if ("markers" in options) {
1184
- let markerStr = "";
1185
- const hasIcon = "markerIcon" in options;
1186
- if (hasIcon) {
1187
- markerStr += `icon:${options.markerIcon}|`;
1188
- }
1189
- if (hasIcon && "markerAnchor" in options) {
1190
- markerStr += `anchor:${options.markerAnchor}|`;
1191
- }
1192
- if (hasIcon && options.hiDPI) {
1193
- markerStr += `scale:2|`;
1194
- }
1195
- const markerList = Array.isArray(options.markers[0]) ? options.markers : [options.markers];
1196
- markerStr += markerList.map((m) => staticMapMarkerToString(m, !hasIcon)).join("|");
1197
- endpoint.searchParams.set("markers", markerStr);
1198
- }
1199
- if ("path" in options) {
1200
- let pathStr = "";
1201
- pathStr += `fill:${options.pathFillColor ?? "none"}|`;
1202
- if ("pathStrokeColor" in options) {
1203
- pathStr += `stroke:${options.pathStrokeColor}|`;
1204
- }
1205
- if ("pathWidth" in options) {
1206
- const pathWidth = options.pathWidth / (options.hiDPI ? 2 : 1);
1207
- pathStr += `width:${pathWidth.toString()}|`;
1208
- }
1209
- pathStr += simplifyAndStringify(options.path);
1210
- endpoint.searchParams.set("path", pathStr);
1211
- }
1212
- endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
1213
- return endpoint.toString();
1214
- }
1215
- const staticMaps = {
1216
- centered,
1217
- bounded,
1218
- automatic
1219
- };
1220
-
1221
- function d(n){return n*Math.PI/180}function _(n){return n%1!==0}var I={};function y(n,t){if(n<0||n>30)throw Error("Invalid zoom level");return _(n)?L(n,t):(I[t]===void 0&&(I[t]={}),Array.isArray(I[t][n])||(I[t][n]=L(n,t)),I[t][n])}function L(n,t){let r=t*Math.pow(2,n);return [r/360,r/(2*Math.PI),r/2,r]}function l(n,t,r=!1,u=512){let{min:o,max:e,sin:s,log:m,round:c}=Math,[a,p,A,i]=y(t,u),M=r?2:1,R=A,f=o(e(s(d(n[1])),-.9999),.9999),P=R+n[0]*a,b=R+.5*m((1+f)/(1-f))*-p;return _(t)||(P=c(P),b=c(b)),P>i*M&&(P=i*M),b>i&&(b=i),[P,b]}function g(n,t=512){let{floor:r}=Math,u=r(n[0]/t),o=r(n[1]/t);return [u,o]}function Z(n,t,r=512){let u=l(n,t,!1,r);return g(u,r)}function w(n,t,r=512){let[u,o,e]=t,s=l(n,u,!1,r),m=o*r,c=e*r;return [(s[0]-m)/r,(s[1]-c)/r]}
1222
-
1223
- const earthRadius = 63710088e-1;
1224
- function mToFt(m) {
1225
- return m * 3.28084;
1226
- }
1227
- function degToRad(degrees) {
1228
- return degrees % 360 * Math.PI / 180;
1229
- }
1230
- function radToDeg(radians) {
1231
- return radians * 180 / Math.PI;
1232
- }
1233
- function getZoomLevelResolution(latitude, zoom, tileSize = 512) {
1234
- return Math.cos(latitude * Math.PI / 180) * 2 * Math.PI * 6378137 / (tileSize * 2 ** zoom) * 3;
1235
- }
1236
- function xyzToTileID(x, y, zoom) {
1237
- return ((1 << zoom) * y + x) * 32 + zoom;
1238
- }
1239
-
1240
- function area(area2) {
1241
- const geometry = "geometry" in area2 ? area2.geometry : area2;
1242
- const type = geometry.type;
1243
- if (type === "MultiPolygon") {
1244
- return multiPolygonArea(geometry.coordinates);
1245
- }
1246
- return polygonArea(geometry.coordinates);
1247
- }
1248
- function multiPolygonArea(multiPoly) {
1249
- const coords = "coordinates" in multiPoly ? multiPoly.coordinates : multiPoly;
1250
- let total = 0;
1251
- for (const polygon of coords) {
1252
- total += polygonArea(polygon);
1253
- }
1254
- return total;
1255
- }
1256
- function polygonArea(poly) {
1257
- const coords = "coordinates" in poly ? poly.coordinates : poly;
1258
- let total = 0;
1259
- for (const ring of coords) {
1260
- total += ringArea(ring);
1261
- }
1262
- return total;
1263
- }
1264
- function ringArea(coords) {
1265
- let p1;
1266
- let p2;
1267
- let p3;
1268
- let lowerIndex;
1269
- let middleIndex;
1270
- let upperIndex;
1271
- let i;
1272
- let total = 0;
1273
- const coordsLength = coords.length;
1274
- if (coordsLength > 2) {
1275
- for (i = 0; i < coordsLength; i++) {
1276
- if (i === coordsLength - 2) {
1277
- lowerIndex = coordsLength - 2;
1278
- middleIndex = coordsLength - 1;
1279
- upperIndex = 0;
1280
- } else if (i === coordsLength - 1) {
1281
- lowerIndex = coordsLength - 1;
1282
- middleIndex = 0;
1283
- upperIndex = 1;
1284
- } else {
1285
- lowerIndex = i;
1286
- middleIndex = i + 1;
1287
- upperIndex = i + 2;
1288
- }
1289
- p1 = coords[lowerIndex];
1290
- p2 = coords[middleIndex];
1291
- p3 = coords[upperIndex];
1292
- total += (degToRad(p3[0]) - degToRad(p1[0])) * Math.sin(degToRad(p2[1]));
1293
- }
1294
- total = total * earthRadius * earthRadius / 2;
1295
- }
1296
- return Math.abs(total);
1297
- }
1298
-
1299
- function lineDistance(line) {
1300
- const coordinates = "geometry" in line ? line.geometry.coordinates : "coordinates" in line ? line.coordinates : line;
1301
- let distance = 0;
1302
- let prevCoord;
1303
- for (const coordinate of coordinates) {
1304
- if (prevCoord !== void 0) {
1305
- distance += pointDistance(prevCoord, coordinate);
1306
- }
1307
- prevCoord = coordinate;
1308
- }
1309
- return distance;
1310
- }
1311
- function pointDistance(from, to) {
1312
- const { pow, sin, cos, sqrt, atan2 } = Math;
1313
- const dLat = degToRad(to[1] - from[1]);
1314
- const dLon = degToRad(to[0] - from[0]);
1315
- const lat1 = degToRad(from[1]);
1316
- const lat2 = degToRad(to[1]);
1317
- const a = pow(sin(dLat / 2), 2) + pow(sin(dLon / 2), 2) * cos(lat1) * cos(lat2);
1318
- return 2 * atan2(sqrt(a), sqrt(1 - a)) * earthRadius;
1319
- }
1320
-
1321
- function tileCover(coordinates, zoom, tileSize) {
1322
- const tileHash = /* @__PURE__ */ new Map();
1323
- const tiles = [];
1324
- const coords = [];
1325
- const resolution = getZoomLevelResolution(coordinates[0][1], zoom, tileSize);
1326
- const samples = sampleProfileLine(coordinates, resolution);
1327
- for (const sample of samples) {
1328
- const coordinate = sample;
1329
- const [tileX, tileY] = Z(coordinate, zoom, tileSize);
1330
- const id = xyzToTileID(tileX, tileY, zoom);
1331
- const tile = { id, x: tileX, y: tileY, z: zoom };
1332
- tileHash.set(id, tile);
1333
- coords.push({ coordinate, tile });
1334
- }
1335
- for (const tile of tileHash.values())
1336
- tiles.push(tile);
1337
- return { coords, tiles };
1338
- }
1339
- function sampleProfileLine(coordinates, resolution) {
1340
- const samples = [];
1341
- let prevCoord;
1342
- for (const coord of coordinates) {
1343
- if (prevCoord !== void 0) {
1344
- const dist = pointDistance(
1345
- prevCoord,
1346
- coord
1347
- );
1348
- const numSamples = Math.ceil(dist / resolution);
1349
- for (let i = 0; i <= numSamples - 1; i++) {
1350
- const sample = [
1351
- prevCoord[0] + (coord[0] - prevCoord[0]) * (i / numSamples),
1352
- prevCoord[1] + (coord[1] - prevCoord[1]) * (i / numSamples)
1353
- ];
1354
- samples.push(sample);
1355
- }
1356
- } else {
1357
- samples.push(coord);
1358
- }
1359
- prevCoord = coord;
1360
- }
1361
- return samples;
1362
- }
1363
-
1364
- function getElevation(coord, tile, tileSize, tileImage, elevationParser = defaultElevationParser) {
1365
- const { channels, image } = tileImage;
1366
- let [x, y] = w(coord, tile, tileSize);
1367
- x = clampPixel(x, tileSize);
1368
- y = clampPixel(y, tileSize);
1369
- const index = (y * tileSize + x) * channels;
1370
- return elevationParser(
1371
- image[index],
1372
- image[index + 1],
1373
- image[index + 2],
1374
- channels === 4 ? image[index + 3] : 0
1375
- );
1376
- }
1377
- function clampPixel(n, tileSize) {
1378
- return Math.max(0, Math.min(tileSize, Math.floor(n * tileSize)));
1379
- }
1380
- function defaultElevationParser(r, g, b) {
1381
- return -1e4 + (r * 256 * 256 + g * 256 + b) * 0.1;
1382
- }
1383
-
1384
- async function profileLineString(path, options) {
1385
- const coordinates = "geometry" in path ? path.geometry.coordinates : path.coordinates;
1386
- const { coords, tiles } = tileCover(
1387
- coordinates,
1388
- options.zoom ?? 13,
1389
- options.tileSize ?? 512
1390
- );
1391
- const tileCache = await getTiles(tiles, options.tileRequest);
1392
- let points = getElevations(
1393
- coords,
1394
- tileCache,
1395
- options.tileSize ?? 512,
1396
- options.elevationParser
1397
- );
1398
- if (options.smooth === true)
1399
- points = smoothElevation(points);
1400
- let output = buildOutput(points);
1401
- if (options.metric === "ft")
1402
- output = toFeet(output);
1403
- return output;
1404
- }
1405
- async function getTiles(tiles, tileRequest) {
1406
- const tileCache = /* @__PURE__ */ new Map();
1407
- const requests = [];
1408
- for (const tile of tiles) {
1409
- requests.push(
1410
- tileRequest(tile.x, tile.y, tile.z).then((res) => {
1411
- tileCache.set(tile.id, res);
1412
- return res;
1413
- }).catch((err) => {
1414
- console.error(err);
1415
- return void 0;
1416
- })
1417
- );
1418
- }
1419
- await Promise.allSettled(requests);
1420
- return tileCache;
1421
- }
1422
- function getElevations(coords, tileCache, tileSize, elevationParser) {
1423
- const points = [];
1424
- let curDistance = 0;
1425
- let prevCoord;
1426
- for (const { tile, coordinate } of coords) {
1427
- const cTile = tileCache.get(tile.id);
1428
- if (cTile === void 0)
1429
- throw new Error(
1430
- `Missing tile ${tile.id} (${tile.x}-${tile.y}-${tile.z})`
1431
- );
1432
- const elevation = getElevation(
1433
- coordinate,
1434
- [tile.z, tile.x, tile.y],
1435
- tileSize,
1436
- cTile,
1437
- elevationParser
1438
- );
1439
- points.push({
1440
- distance: curDistance,
1441
- elevation,
1442
- coordinate,
1443
- tile
1444
- });
1445
- if (prevCoord !== void 0) {
1446
- curDistance += pointDistance(prevCoord, coordinate);
1447
- }
1448
- prevCoord = coordinate;
1449
- }
1450
- return points;
1451
- }
1452
- function buildOutput(points) {
1453
- let minElevation = Infinity;
1454
- let maxElevation = -Infinity;
1455
- let totalElevation = 0;
1456
- for (const point of points) {
1457
- if (point.elevation < minElevation)
1458
- minElevation = point.elevation;
1459
- if (point.elevation > maxElevation)
1460
- maxElevation = point.elevation;
1461
- totalElevation += point.elevation;
1462
- }
1463
- return {
1464
- distance: points[points.length - 1].distance,
1465
- minElevation,
1466
- maxElevation,
1467
- avgElevation: totalElevation / points.length,
1468
- startElevation: points[0].elevation,
1469
- endElevation: points[points.length - 1].elevation,
1470
- points
1471
- };
1472
- }
1473
- function smoothElevation(points) {
1474
- const newPoints = [];
1475
- let prevPoint;
1476
- for (let i = 0; i < points.length; i++) {
1477
- const point = points[i];
1478
- const nextPoint = points[i + 1] ?? points[i];
1479
- if (prevPoint === void 0) {
1480
- newPoints.push(point);
1481
- } else {
1482
- const newPoint = {
1483
- distance: point.distance,
1484
- elevation: (prevPoint.elevation + point.elevation + nextPoint.elevation) / 3,
1485
- coordinate: point.coordinate,
1486
- tile: point.tile
1487
- };
1488
- newPoints.push(newPoint);
1489
- }
1490
- prevPoint = point;
1491
- }
1492
- return newPoints;
1493
- }
1494
- function toFeet(input) {
1495
- const output = {
1496
- distance: mToFt(input.distance),
1497
- minElevation: mToFt(input.minElevation),
1498
- maxElevation: mToFt(input.maxElevation),
1499
- avgElevation: mToFt(input.avgElevation),
1500
- startElevation: mToFt(input.startElevation),
1501
- endElevation: mToFt(input.endElevation),
1502
- points: input.points.map(({ distance, elevation, coordinate, tile }) => ({
1503
- distance: mToFt(distance),
1504
- elevation: mToFt(elevation),
1505
- coordinate,
1506
- tile
1507
- }))
1508
- };
1509
- return output;
1510
- }
1511
-
1512
- exports.ClientConfig = ClientConfig;
1513
- exports.LanguageGeocoding = LanguageGeocoding;
1514
- exports.MapStyle = MapStyle;
1515
- exports.MapStyleVariant = MapStyleVariant;
1516
- exports.ReferenceMapStyle = ReferenceMapStyle;
1517
- exports.ServiceError = ServiceError;
1518
- exports.area = area;
1519
- exports.config = config;
1520
- exports.coordinates = coordinates;
1521
- exports.data = data;
1522
- exports.defaultElevationParser = defaultElevationParser;
1523
- exports.degToRad = degToRad;
1524
- exports.earthRadius = earthRadius;
1525
- exports.expandMapStyle = expandMapStyle;
1526
- exports.geocoding = geocoding;
1527
- exports.geolocation = geolocation;
1528
- exports.getZoomLevelResolution = getZoomLevelResolution;
1529
- exports.lineDistance = lineDistance;
1530
- exports.mToFt = mToFt;
1531
- exports.mapStylePresetList = mapStylePresetList;
1532
- exports.multiPolygonArea = multiPolygonArea;
1533
- exports.pointDistance = pointDistance;
1534
- exports.polygonArea = polygonArea;
1535
- exports.profileLineString = profileLineString;
1536
- exports.radToDeg = radToDeg;
1537
- exports.staticMaps = staticMaps;
1538
- exports.xyzToTileID = xyzToTileID;
1539
-
1540
- }));
1541
- //# sourceMappingURL=maptiler-client.umd.js.map