@maptiler/client 1.6.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 (118) 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 +587 -332
  5. package/dist/maptiler-client.cjs.map +1 -1
  6. package/dist/maptiler-client.d.ts +291 -12
  7. package/dist/maptiler-client.min.mjs +1 -1
  8. package/dist/maptiler-client.mjs +580 -332
  9. package/dist/maptiler-client.mjs.map +1 -1
  10. package/package.json +29 -20
  11. package/readme.md +134 -2
  12. package/rollup.config.js +3 -3
  13. package/tsconfig.json +1 -1
  14. package/dist/maptiler-client.umd.js +0 -1368
  15. package/dist/maptiler-client.umd.js.map +0 -1
  16. package/dist/maptiler-client.umd.min.js +0 -1
  17. package/docs/.nojekyll +0 -1
  18. package/docs/assets/custom.css +0 -118
  19. package/docs/assets/highlight.css +0 -85
  20. package/docs/assets/main.js +0 -58
  21. package/docs/assets/search.js +0 -1
  22. package/docs/assets/style.css +0 -1280
  23. package/docs/classes/config.ClientConfig.html +0 -132
  24. package/docs/classes/services_ServiceError.ServiceError.html +0 -103
  25. package/docs/functions/language.getAutoLanguageGeocoding.html +0 -60
  26. package/docs/functions/services_simplify.default.html +0 -65
  27. package/docs/images/JS-logo.svg +0 -4
  28. package/docs/images/TS-logo.svg +0 -6
  29. package/docs/images/maptiler-client-logo.afdesign +0 -0
  30. package/docs/images/maptiler-client-logo.svg +0 -75
  31. package/docs/images/maptiler-logo-256.png +0 -0
  32. package/docs/images/maptiler-logo.svg +0 -23
  33. package/docs/images/screenshots/static-bounded-europe-1024.png +0 -0
  34. package/docs/images/screenshots/static-bounded-europe-2048.png +0 -0
  35. package/docs/images/screenshots/static-bounded-portugal-1024x2048.png +0 -0
  36. package/docs/images/screenshots/static-bounded-portugal-2048x2048.png +0 -0
  37. package/docs/images/screenshots/static-with-path.png +0 -0
  38. package/docs/index.html +0 -340
  39. package/docs/modules/config.html +0 -71
  40. package/docs/modules/language.html +0 -71
  41. package/docs/modules/services_ServiceError.html +0 -61
  42. package/docs/modules/services_coordinates.html +0 -84
  43. package/docs/modules/services_data.html +0 -66
  44. package/docs/modules/services_geocoding.html +0 -82
  45. package/docs/modules/services_geolocation.html +0 -68
  46. package/docs/modules/services_simplify.html +0 -61
  47. package/docs/modules/services_staticMaps.html +0 -74
  48. package/docs/modules.html +0 -59
  49. package/docs/types/config.FetchFunction.html +0 -71
  50. package/docs/types/language.LanguageGeocodingString.html +0 -58
  51. package/docs/types/services_coordinates.CoordinateExport.html +0 -71
  52. package/docs/types/services_coordinates.CoordinateGrid.html +0 -69
  53. package/docs/types/services_coordinates.CoordinateId.html +0 -71
  54. package/docs/types/services_coordinates.CoordinateSearch.html +0 -93
  55. package/docs/types/services_coordinates.CoordinateSearchResult.html +0 -75
  56. package/docs/types/services_coordinates.CoordinateTransformResult.html +0 -76
  57. package/docs/types/services_coordinates.CoordinateTransformation.html +0 -89
  58. package/docs/types/services_coordinates.CoordinatesSearchOptions.html +0 -83
  59. package/docs/types/services_coordinates.CoordinatesTransformOptions.html +0 -85
  60. package/docs/types/services_coordinates.XYZ.html +0 -73
  61. package/docs/types/services_data.GetDataOptions.html +0 -64
  62. package/docs/types/services_geocoding.ByIdGeocodingOptions.html +0 -63
  63. package/docs/types/services_geocoding.CommonForwardAndReverseGeocodingOptions.html +0 -63
  64. package/docs/types/services_geocoding.Coordinates.html +0 -63
  65. package/docs/types/services_geocoding.FeatureHierarchy.html +0 -63
  66. package/docs/types/services_geocoding.GeocodingFeature.html +0 -63
  67. package/docs/types/services_geocoding.GeocodingOptions.html +0 -63
  68. package/docs/types/services_geocoding.GeocodingSearchResult.html +0 -80
  69. package/docs/types/services_geocoding.LanguageGeocodingOptions.html +0 -70
  70. package/docs/types/services_geocoding.ReverseGeocodingOptions.html +0 -63
  71. package/docs/types/services_geolocation.GeolocationInfoOptions.html +0 -65
  72. package/docs/types/services_geolocation.GeolocationResult.html +0 -128
  73. package/docs/types/services_staticMaps.AutomaticStaticMapOptions.html +0 -61
  74. package/docs/types/services_staticMaps.BoundedStaticMapOptions.html +0 -61
  75. package/docs/types/services_staticMaps.CenteredStaticMapOptions.html +0 -61
  76. package/docs/types/services_staticMaps.StaticMapBaseOptions.html +0 -157
  77. package/docs/types/services_staticMaps.StaticMapMarker.html +0 -61
  78. package/docs/variables/config.config.html +0 -58
  79. package/docs/variables/language.LanguageGeocoding.html +0 -171
  80. package/docs/variables/services_coordinates.coordinates.html +0 -110
  81. package/docs/variables/services_data.data.html +0 -80
  82. package/docs/variables/services_geocoding.geocoding.html +0 -265
  83. package/docs/variables/services_geolocation.geolocation.html +0 -79
  84. package/docs/variables/services_staticMaps.staticMaps.html +0 -128
  85. package/docsmd/.nojekyll +0 -1
  86. package/docsmd/README.md +0 -873
  87. package/docsmd/assets/custom.css +0 -118
  88. package/docsmd/classes/ClientConfig.md +0 -90
  89. package/docsmd/classes/MapStyleVariant.md +0 -234
  90. package/docsmd/classes/ReferenceMapStyle.md +0 -169
  91. package/docsmd/classes/ServiceError.md +0 -52
  92. package/examples/test-browser-es.html +0 -103
  93. package/examples/test-browser-umd.html +0 -90
  94. package/examples/test-node.js +0 -52
  95. package/images/JS-logo.svg +0 -4
  96. package/images/TS-logo.svg +0 -6
  97. package/images/maptiler-client-logo.afdesign +0 -0
  98. package/images/maptiler-client-logo.svg +0 -75
  99. package/images/maptiler-logo-256.png +0 -0
  100. package/images/maptiler-logo.svg +0 -23
  101. package/images/screenshots/static-bounded-europe-1024.png +0 -0
  102. package/images/screenshots/static-bounded-europe-2048.png +0 -0
  103. package/images/screenshots/static-bounded-portugal-1024x2048.png +0 -0
  104. package/images/screenshots/static-bounded-portugal-2048x2048.png +0 -0
  105. package/images/screenshots/static-with-path.png +0 -0
  106. package/src/callFetch.ts +0 -18
  107. package/src/config.ts +0 -65
  108. package/src/defaults.ts +0 -11
  109. package/src/index.ts +0 -111
  110. package/src/language.ts +0 -87
  111. package/src/mapstyle.ts +0 -968
  112. package/src/services/ServiceError.ts +0 -10
  113. package/src/services/coordinates.ts +0 -258
  114. package/src/services/data.ts +0 -63
  115. package/src/services/geocoding.ts +0 -458
  116. package/src/services/geolocation.ts +0 -139
  117. package/src/services/simplify.ts +0 -87
  118. package/src/services/staticMaps.ts +0 -463
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- Object.defineProperty(exports, '__esModule', { value: true });
3
+ var QuickLRU = require('quick-lru');
4
4
 
5
5
  function tryGettingFetch() {
6
6
  if (typeof self !== "undefined") {
@@ -22,6 +22,10 @@ class ClientConfig {
22
22
  * will be automatically resolved.
23
23
  */
24
24
  this._fetch = tryGettingFetch();
25
+ /**
26
+ * Number of tiles to keep in cache
27
+ */
28
+ this.tileCacheSize = 200;
25
29
  }
26
30
  /**
27
31
  * Set the MapTiler Cloud API key
@@ -118,40 +122,18 @@ function getAutoLanguageGeocoding() {
118
122
  return canditatelangs.length ? canditatelangs[0] : LanguageGeocoding.ENGLISH;
119
123
  }
120
124
 
121
- var __async$4 = (__this, __arguments, generator) => {
122
- return new Promise((resolve, reject) => {
123
- var fulfilled = (value) => {
124
- try {
125
- step(generator.next(value));
126
- } catch (e) {
127
- reject(e);
128
- }
129
- };
130
- var rejected = (value) => {
131
- try {
132
- step(generator.throw(value));
133
- } catch (e) {
134
- reject(e);
135
- }
136
- };
137
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
138
- step((generator = generator.apply(__this, __arguments)).next());
139
- });
140
- };
141
- function callFetch(_0) {
142
- return __async$4(this, arguments, function* (resource, options = {}) {
143
- if (config.fetch === null) {
144
- throw new Error(
145
- "The fetch function was not found. If on NodeJS < 18 please specify the fetch function with config.fetch"
146
- );
147
- }
148
- if (new URL(resource).searchParams.get("key").trim() === "") {
149
- throw new Error(
150
- "The MapTiler Cloud API key is missing. Set it in `config.apiKey` or get one for free at https://maptiler.com"
151
- );
152
- }
153
- return config.fetch(resource, options);
154
- });
125
+ async function callFetch(resource, options = {}) {
126
+ if (config.fetch === null) {
127
+ throw new Error(
128
+ "The fetch function was not found. If on NodeJS < 18 please specify the fetch function with config.fetch"
129
+ );
130
+ }
131
+ if (new URL(resource).searchParams.get("key").trim() === "") {
132
+ throw new Error(
133
+ "The MapTiler Cloud API key is missing. Set it in `config.apiKey` or get one for free at https://maptiler.com"
134
+ );
135
+ }
136
+ return config.fetch(resource, options);
155
137
  }
156
138
 
157
139
  const defaults = {
@@ -169,37 +151,18 @@ class ServiceError extends Error {
169
151
  }
170
152
  }
171
153
 
172
- var __async$3 = (__this, __arguments, generator) => {
173
- return new Promise((resolve, reject) => {
174
- var fulfilled = (value) => {
175
- try {
176
- step(generator.next(value));
177
- } catch (e) {
178
- reject(e);
179
- }
180
- };
181
- var rejected = (value) => {
182
- try {
183
- step(generator.throw(value));
184
- } catch (e) {
185
- reject(e);
186
- }
187
- };
188
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
189
- step((generator = generator.apply(__this, __arguments)).next());
190
- });
191
- };
192
- const customMessages$3 = {
154
+ const customMessages$4 = {
193
155
  400: "Query too long / Invalid parameters",
194
156
  403: "Key is missing, invalid or restricted"
195
157
  };
196
158
  function addLanguageGeocodingOptions(searchParams, options) {
197
- if (options.language == void 0) {
159
+ const { language } = options;
160
+ if (language == void 0) {
198
161
  return;
199
162
  }
200
163
  const languages = Array.from(
201
164
  new Set(
202
- (Array.isArray(options.language) ? options.language : [options.language]).map(
165
+ (Array.isArray(language) ? language : [language]).map(
203
166
  (lang) => lang === LanguageGeocoding.AUTO ? getAutoLanguageGeocoding() : lang
204
167
  )
205
168
  )
@@ -207,304 +170,228 @@ function addLanguageGeocodingOptions(searchParams, options) {
207
170
  searchParams.set("language", languages);
208
171
  }
209
172
  function addCommonForwardAndReverseGeocodingOptions(searchParams, options) {
210
- var _a;
211
- searchParams.set("key", (_a = options.apiKey) != null ? _a : config.apiKey);
212
- if (options.limit != void 0) {
213
- searchParams.set("limit", String(options.limit));
173
+ const { apiKey, limit, types, excludeTypes } = options;
174
+ searchParams.set("key", apiKey ?? config.apiKey);
175
+ if (limit != void 0) {
176
+ searchParams.set("limit", String(limit));
177
+ }
178
+ if (types != void 0) {
179
+ searchParams.set("types", types.join(","));
214
180
  }
215
- if (options.types != void 0) {
216
- searchParams.set("types", options.types.join(","));
181
+ if (excludeTypes != void 0) {
182
+ searchParams.set("excludeTypes", String(excludeTypes));
217
183
  }
218
184
  addLanguageGeocodingOptions(searchParams, options);
219
185
  }
220
186
  function addForwardGeocodingOptions(searchParams, options) {
221
187
  addCommonForwardAndReverseGeocodingOptions(searchParams, options);
222
- if (options.bbox != void 0) {
223
- searchParams.set("bbox", options.bbox.join(","));
224
- }
225
- if (options.proximity != void 0) {
226
- searchParams.set("proximity", options.proximity.join(","));
188
+ const { bbox, proximity, country, fuzzyMatch, autocomplete } = options;
189
+ if (bbox != void 0) {
190
+ searchParams.set("bbox", bbox.join(","));
191
+ }
192
+ if (proximity != void 0) {
193
+ searchParams.set(
194
+ "proximity",
195
+ proximity === "ip" ? proximity : proximity.join(",")
196
+ );
227
197
  }
228
- if (options.country != void 0) {
229
- searchParams.set("country", options.country.join(","));
198
+ if (country != void 0) {
199
+ searchParams.set("country", country.join(","));
230
200
  }
231
- if (options.fuzzyMatch != void 0) {
232
- searchParams.set("fuzzyMatch", options.fuzzyMatch ? "true" : "false");
201
+ if (fuzzyMatch != void 0) {
202
+ searchParams.set("fuzzyMatch", fuzzyMatch ? "true" : "false");
233
203
  }
234
- if (options.autocomplete != void 0) {
235
- searchParams.set("autocomplete", options.autocomplete ? "true" : "false");
204
+ if (autocomplete != void 0) {
205
+ searchParams.set("autocomplete", autocomplete ? "true" : "false");
236
206
  }
237
207
  }
238
- function forward(_0) {
239
- return __async$3(this, arguments, function* (query, options = {}) {
240
- var _a;
241
- if (typeof query !== "string" || query.trim().length === 0) {
242
- throw new Error("The query must be a non-empty string");
243
- }
244
- const endpoint = new URL(
245
- `geocoding/${encodeURIComponent(query)}.json`,
246
- defaults.maptilerApiURL
247
- );
248
- const { searchParams } = endpoint;
249
- addForwardGeocodingOptions(searchParams, options);
250
- const urlWithParams = endpoint.toString();
251
- const res = yield callFetch(urlWithParams);
252
- if (!res.ok) {
253
- throw new ServiceError(res, (_a = customMessages$3[res.status]) != null ? _a : "");
254
- }
255
- const obj = yield res.json();
256
- return obj;
257
- });
208
+ async function forward(query, options = {}) {
209
+ if (typeof query !== "string" || query.trim().length === 0) {
210
+ throw new Error("The query must be a non-empty string");
211
+ }
212
+ const endpoint = new URL(
213
+ `geocoding/${encodeURIComponent(query)}.json`,
214
+ defaults.maptilerApiURL
215
+ );
216
+ const { searchParams } = endpoint;
217
+ addForwardGeocodingOptions(searchParams, options);
218
+ const urlWithParams = endpoint.toString();
219
+ const res = await callFetch(urlWithParams);
220
+ if (!res.ok) {
221
+ throw new ServiceError(res, customMessages$4[res.status] ?? "");
222
+ }
223
+ const obj = await res.json();
224
+ return obj;
258
225
  }
259
- function reverse(_0) {
260
- return __async$3(this, arguments, function* (position, options = {}) {
261
- var _a;
262
- if (!Array.isArray(position) || position.length < 2) {
263
- throw new Error("The position must be an array of form [lng, lat].");
264
- }
265
- const endpoint = new URL(
266
- `geocoding/${position[0]},${position[1]}.json`,
267
- defaults.maptilerApiURL
268
- );
269
- addCommonForwardAndReverseGeocodingOptions(endpoint.searchParams, options);
270
- const urlWithParams = endpoint.toString();
271
- const res = yield callFetch(urlWithParams);
272
- if (!res.ok) {
273
- throw new ServiceError(res, (_a = customMessages$3[res.status]) != null ? _a : "");
274
- }
275
- const obj = yield res.json();
276
- return obj;
277
- });
226
+ async function reverse(position, options = {}) {
227
+ if (!Array.isArray(position) || position.length < 2) {
228
+ throw new Error("The position must be an array of form [lng, lat].");
229
+ }
230
+ const endpoint = new URL(
231
+ `geocoding/${position[0]},${position[1]}.json`,
232
+ defaults.maptilerApiURL
233
+ );
234
+ addCommonForwardAndReverseGeocodingOptions(endpoint.searchParams, options);
235
+ const urlWithParams = endpoint.toString();
236
+ const res = await callFetch(urlWithParams);
237
+ if (!res.ok) {
238
+ throw new ServiceError(res, customMessages$4[res.status] ?? "");
239
+ }
240
+ const obj = await res.json();
241
+ return obj;
278
242
  }
279
- function byId(_0) {
280
- return __async$3(this, arguments, function* (id, options = {}) {
281
- var _a;
282
- const endpoint = new URL(`geocoding/${id}.json`, defaults.maptilerApiURL);
283
- addLanguageGeocodingOptions(endpoint.searchParams, options);
284
- const urlWithParams = endpoint.toString();
285
- const res = yield callFetch(urlWithParams);
286
- if (!res.ok) {
287
- throw new ServiceError(res, (_a = customMessages$3[res.status]) != null ? _a : "");
288
- }
289
- const obj = yield res.json();
290
- return obj;
291
- });
243
+ async function byId(id, options = {}) {
244
+ const endpoint = new URL(`geocoding/${id}.json`, defaults.maptilerApiURL);
245
+ endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
246
+ addLanguageGeocodingOptions(endpoint.searchParams, options);
247
+ const urlWithParams = endpoint.toString();
248
+ const res = await callFetch(urlWithParams);
249
+ if (!res.ok) {
250
+ throw new ServiceError(res, customMessages$4[res.status] ?? "");
251
+ }
252
+ const obj = await res.json();
253
+ return obj;
292
254
  }
293
- function batch(_0) {
294
- return __async$3(this, arguments, function* (queries, options = {}) {
295
- var _a;
296
- if (!queries.length) {
297
- return [];
298
- }
299
- const joinedQuery = queries.map((query) => encodeURIComponent(query)).join(";");
300
- const endpoint = new URL(
301
- `geocoding/${joinedQuery}.json`,
302
- defaults.maptilerApiURL
303
- );
304
- const { searchParams } = endpoint;
305
- addForwardGeocodingOptions(searchParams, options);
306
- const urlWithParams = endpoint.toString();
307
- const res = yield callFetch(urlWithParams);
308
- if (!res.ok) {
309
- throw new ServiceError(res, (_a = customMessages$3[res.status]) != null ? _a : "");
310
- }
311
- const obj = yield res.json();
312
- return queries.length === 1 ? [obj] : obj;
313
- });
255
+ async function batch$1(queries, options = {}) {
256
+ if (!queries.length) {
257
+ return [];
258
+ }
259
+ const joinedQuery = queries.map((query) => encodeURIComponent(query)).join(";");
260
+ const endpoint = new URL(
261
+ `geocoding/${joinedQuery}.json`,
262
+ defaults.maptilerApiURL
263
+ );
264
+ const { searchParams } = endpoint;
265
+ addForwardGeocodingOptions(searchParams, options);
266
+ const urlWithParams = endpoint.toString();
267
+ const res = await callFetch(urlWithParams);
268
+ if (!res.ok) {
269
+ throw new ServiceError(res, customMessages$4[res.status] ?? "");
270
+ }
271
+ const obj = await res.json();
272
+ return queries.length === 1 ? [obj] : obj;
314
273
  }
315
274
  const geocoding = {
316
275
  forward,
317
276
  reverse,
318
277
  byId,
319
- batch,
278
+ batch: batch$1,
320
279
  language: LanguageGeocoding
321
280
  };
322
281
 
323
- var __async$2 = (__this, __arguments, generator) => {
324
- return new Promise((resolve, reject) => {
325
- var fulfilled = (value) => {
326
- try {
327
- step(generator.next(value));
328
- } catch (e) {
329
- reject(e);
330
- }
331
- };
332
- var rejected = (value) => {
333
- try {
334
- step(generator.throw(value));
335
- } catch (e) {
336
- reject(e);
337
- }
338
- };
339
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
340
- step((generator = generator.apply(__this, __arguments)).next());
341
- });
342
- };
343
- const customMessages$2 = {
282
+ const customMessages$3 = {
344
283
  403: "Key is missing, invalid or restricted"
345
284
  };
346
- function info() {
347
- return __async$2(this, arguments, function* (options = {}) {
348
- var _a;
349
- const endpoint = new URL(`geolocation/ip.json`, defaults.maptilerApiURL);
350
- endpoint.searchParams.set("key", (_a = options.apiKey) != null ? _a : config.apiKey);
351
- const urlWithParams = endpoint.toString();
352
- const res = yield callFetch(urlWithParams);
353
- if (!res.ok) {
354
- throw new ServiceError(
355
- res,
356
- res.status in customMessages$2 ? customMessages$2[res.status] : ""
357
- );
358
- }
359
- const obj = yield res.json();
360
- return obj;
361
- });
285
+ async function info(options = {}) {
286
+ const endpoint = new URL(`geolocation/ip.json`, defaults.maptilerApiURL);
287
+ endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
288
+ const urlWithParams = endpoint.toString();
289
+ const res = await callFetch(urlWithParams);
290
+ if (!res.ok) {
291
+ throw new ServiceError(
292
+ res,
293
+ res.status in customMessages$3 ? customMessages$3[res.status] : ""
294
+ );
295
+ }
296
+ const obj = await res.json();
297
+ return obj;
362
298
  }
363
299
  const geolocation = {
364
300
  info
365
301
  };
366
302
 
367
- var __async$1 = (__this, __arguments, generator) => {
368
- return new Promise((resolve, reject) => {
369
- var fulfilled = (value) => {
370
- try {
371
- step(generator.next(value));
372
- } catch (e) {
373
- reject(e);
374
- }
375
- };
376
- var rejected = (value) => {
377
- try {
378
- step(generator.throw(value));
379
- } catch (e) {
380
- reject(e);
381
- }
382
- };
383
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
384
- step((generator = generator.apply(__this, __arguments)).next());
385
- });
386
- };
387
- const customMessages$1 = {
303
+ const customMessages$2 = {
388
304
  403: "Key is missing, invalid or restricted"
389
305
  };
390
- function search(_0) {
391
- return __async$1(this, arguments, function* (query, options = {}) {
392
- var _a;
393
- if (typeof query !== "string" || query.trim().length === 0) {
394
- throw new Error("The query must be a non-empty string");
395
- }
396
- const endpoint = new URL(
397
- `coordinates/search/${query}.json`,
398
- defaults.maptilerApiURL
306
+ async function search(query, options = {}) {
307
+ if (typeof query !== "string" || query.trim().length === 0) {
308
+ throw new Error("The query must be a non-empty string");
309
+ }
310
+ const endpoint = new URL(
311
+ `coordinates/search/${query}.json`,
312
+ defaults.maptilerApiURL
313
+ );
314
+ endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
315
+ if ("limit" in options) {
316
+ endpoint.searchParams.set("limit", options.limit.toString());
317
+ }
318
+ if ("transformations" in options) {
319
+ endpoint.searchParams.set(
320
+ "transformations",
321
+ options.transformations.toString()
399
322
  );
400
- endpoint.searchParams.set("key", (_a = options.apiKey) != null ? _a : config.apiKey);
401
- if ("limit" in options) {
402
- endpoint.searchParams.set("limit", options.limit.toString());
403
- }
404
- if ("transformations" in options) {
405
- endpoint.searchParams.set(
406
- "transformations",
407
- options.transformations.toString()
408
- );
409
- }
410
- if ("exports" in options) {
411
- endpoint.searchParams.set("exports", options.exports.toString());
412
- }
413
- const urlWithParams = endpoint.toString();
414
- const res = yield callFetch(urlWithParams);
415
- if (!res.ok) {
416
- throw new ServiceError(
417
- res,
418
- res.status in customMessages$1 ? customMessages$1[res.status] : ""
419
- );
420
- }
421
- const obj = yield res.json();
422
- return obj;
423
- });
323
+ }
324
+ if ("exports" in options) {
325
+ endpoint.searchParams.set("exports", options.exports.toString());
326
+ }
327
+ const urlWithParams = endpoint.toString();
328
+ const res = await callFetch(urlWithParams);
329
+ if (!res.ok) {
330
+ throw new ServiceError(
331
+ res,
332
+ res.status in customMessages$2 ? customMessages$2[res.status] : ""
333
+ );
334
+ }
335
+ const obj = await res.json();
336
+ return obj;
424
337
  }
425
- function transform(_0) {
426
- return __async$1(this, arguments, function* (positions, options = {}) {
427
- var _a;
428
- const coordinatesStr = (Array.isArray(positions[0]) ? positions : [positions]).map((coord) => `${coord[0]},${coord[1]}`).join(";");
429
- const endpoint = new URL(
430
- `coordinates/transform/${coordinatesStr}.json`,
431
- defaults.maptilerApiURL
338
+ async function transform(positions, options = {}) {
339
+ const coordinatesStr = (Array.isArray(positions[0]) ? positions : [positions]).map((coord) => `${coord[0]},${coord[1]}`).join(";");
340
+ const endpoint = new URL(
341
+ `coordinates/transform/${coordinatesStr}.json`,
342
+ defaults.maptilerApiURL
343
+ );
344
+ endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
345
+ if ("sourceCrs" in options) {
346
+ endpoint.searchParams.set("s_srs", options.sourceCrs.toString());
347
+ }
348
+ if ("targetCrs" in options) {
349
+ endpoint.searchParams.set("t_srs", options.targetCrs.toString());
350
+ }
351
+ if ("operations" in options) {
352
+ endpoint.searchParams.set(
353
+ "ops",
354
+ (Array.isArray(options.operations) ? options.operations : [options.operations]).join("|")
432
355
  );
433
- endpoint.searchParams.set("key", (_a = options.apiKey) != null ? _a : config.apiKey);
434
- if ("sourceCrs" in options) {
435
- endpoint.searchParams.set("s_srs", options.sourceCrs.toString());
436
- }
437
- if ("targetCrs" in options) {
438
- endpoint.searchParams.set("t_srs", options.targetCrs.toString());
439
- }
440
- if ("operations" in options) {
441
- endpoint.searchParams.set(
442
- "ops",
443
- (Array.isArray(options.operations) ? options.operations : [options.operations]).join("|")
444
- );
445
- }
446
- const urlWithParams = endpoint.toString();
447
- const res = yield callFetch(urlWithParams);
448
- if (!res.ok) {
449
- throw new ServiceError(
450
- res,
451
- res.status in customMessages$1 ? customMessages$1[res.status] : ""
452
- );
453
- }
454
- const obj = yield res.json();
455
- return obj;
456
- });
356
+ }
357
+ const urlWithParams = endpoint.toString();
358
+ const res = await callFetch(urlWithParams);
359
+ if (!res.ok) {
360
+ throw new ServiceError(
361
+ res,
362
+ res.status in customMessages$2 ? customMessages$2[res.status] : ""
363
+ );
364
+ }
365
+ const obj = await res.json();
366
+ return obj;
457
367
  }
458
368
  const coordinates = {
459
369
  search,
460
370
  transform
461
371
  };
462
372
 
463
- var __async = (__this, __arguments, generator) => {
464
- return new Promise((resolve, reject) => {
465
- var fulfilled = (value) => {
466
- try {
467
- step(generator.next(value));
468
- } catch (e) {
469
- reject(e);
470
- }
471
- };
472
- var rejected = (value) => {
473
- try {
474
- step(generator.throw(value));
475
- } catch (e) {
476
- reject(e);
477
- }
478
- };
479
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
480
- step((generator = generator.apply(__this, __arguments)).next());
481
- });
482
- };
483
- const customMessages = {
373
+ const customMessages$1 = {
484
374
  403: "Key is missing, invalid or restricted"
485
375
  };
486
- function get(_0) {
487
- return __async(this, arguments, function* (dataId, options = {}) {
488
- var _a;
489
- if (typeof dataId !== "string" || dataId.trim().length === 0) {
490
- throw new Error("The data ID must be a non-empty string");
491
- }
492
- const endpoint = new URL(
493
- `data/${encodeURIComponent(dataId)}/features.json`,
494
- defaults.maptilerApiURL
376
+ async function get(dataId, options = {}) {
377
+ if (typeof dataId !== "string" || dataId.trim().length === 0) {
378
+ throw new Error("The data ID must be a non-empty string");
379
+ }
380
+ const endpoint = new URL(
381
+ `data/${encodeURIComponent(dataId)}/features.json`,
382
+ defaults.maptilerApiURL
383
+ );
384
+ endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
385
+ const urlWithParams = endpoint.toString();
386
+ const res = await callFetch(urlWithParams);
387
+ if (!res.ok) {
388
+ throw new ServiceError(
389
+ res,
390
+ res.status in customMessages$1 ? customMessages$1[res.status] : ""
495
391
  );
496
- endpoint.searchParams.set("key", (_a = options.apiKey) != null ? _a : config.apiKey);
497
- const urlWithParams = endpoint.toString();
498
- const res = yield callFetch(urlWithParams);
499
- if (!res.ok) {
500
- throw new ServiceError(
501
- res,
502
- res.status in customMessages ? customMessages[res.status] : ""
503
- );
504
- }
505
- const obj = yield res.json();
506
- return obj;
507
- });
392
+ }
393
+ const obj = await res.json();
394
+ return obj;
508
395
  }
509
396
  const data = {
510
397
  get
@@ -1107,6 +994,36 @@ function styleToStyle(style) {
1107
994
  }
1108
995
  const MapStyle = buildMapStyles();
1109
996
 
997
+ function extractLineStrings(geoJson) {
998
+ const lineStrings = [];
999
+ function extractFromGeometry(geometry) {
1000
+ if (geometry.type === "LineString" || geometry.type === "MultiLineString") {
1001
+ lineStrings.push(geometry);
1002
+ }
1003
+ }
1004
+ function extractFromFeature(feature) {
1005
+ if (feature.geometry) {
1006
+ extractFromGeometry(feature.geometry);
1007
+ }
1008
+ }
1009
+ function extractFromFeatureCollection(collection) {
1010
+ for (const feature of collection.features) {
1011
+ if (feature.type === "Feature") {
1012
+ extractFromFeature(feature);
1013
+ } else if (feature.type === "FeatureCollection") {
1014
+ extractFromFeatureCollection(feature);
1015
+ }
1016
+ }
1017
+ }
1018
+ if (geoJson.type === "Feature") {
1019
+ extractFromFeature(geoJson);
1020
+ } else if (geoJson.type === "FeatureCollection") {
1021
+ extractFromFeatureCollection(geoJson);
1022
+ } else {
1023
+ extractFromGeometry(geoJson);
1024
+ }
1025
+ return lineStrings;
1026
+ }
1110
1027
  function getSqSegDist(p, p1, p2) {
1111
1028
  let x = p1[0], y = p1[1], dx = p2[0] - x, dy = p2[1] - y;
1112
1029
  if (dx !== 0 || dy !== 0) {
@@ -1157,6 +1074,10 @@ function simplify(points, tolerance) {
1157
1074
  const simplePoints = simplifyDouglasPeucker(points, sqTolerance);
1158
1075
  return simplePoints;
1159
1076
  }
1077
+ const misc = {
1078
+ extractLineStrings,
1079
+ simplify
1080
+ };
1160
1081
 
1161
1082
  function staticMapMarkerToString(marker, includeColor = true) {
1162
1083
  let str = `${marker[0]},${marker[1]}`;
@@ -1170,19 +1091,18 @@ function simplifyAndStringify(path, maxNbChar = 3e3) {
1170
1091
  let tolerance = 5e-6;
1171
1092
  const toleranceStep = 1e-5;
1172
1093
  while (str.length > maxNbChar) {
1173
- const simplerPath = simplify(path, tolerance);
1094
+ const simplerPath = misc.simplify(path, tolerance);
1174
1095
  str = simplerPath.map((point) => `${point[0]},${point[1]}`).join("|");
1175
1096
  tolerance += toleranceStep;
1176
1097
  }
1177
1098
  return str;
1178
1099
  }
1179
1100
  function centered(center, zoom, options = {}) {
1180
- var _a, _b, _c, _d, _e;
1181
1101
  const style = styleToStyle(options.style);
1182
1102
  const scale = options.hiDPI ? "@2x" : "";
1183
- const format = (_a = options.format) != null ? _a : "png";
1184
- let width = ~~((_b = options.width) != null ? _b : 1024);
1185
- let height = ~~((_c = options.height) != null ? _c : 1024);
1103
+ const format = options.format ?? "png";
1104
+ let width = ~~(options.width ?? 1024);
1105
+ let height = ~~(options.height ?? 1024);
1186
1106
  if (options.hiDPI) {
1187
1107
  width = ~~(width / 2);
1188
1108
  height = ~~(height / 2);
@@ -1212,7 +1132,7 @@ function centered(center, zoom, options = {}) {
1212
1132
  }
1213
1133
  if ("path" in options) {
1214
1134
  let pathStr = "";
1215
- pathStr += `fill:${(_d = options.pathFillColor) != null ? _d : "none"}|`;
1135
+ pathStr += `fill:${options.pathFillColor ?? "none"}|`;
1216
1136
  if ("pathStrokeColor" in options) {
1217
1137
  pathStr += `stroke:${options.pathStrokeColor}|`;
1218
1138
  }
@@ -1223,16 +1143,15 @@ function centered(center, zoom, options = {}) {
1223
1143
  pathStr += simplifyAndStringify(options.path);
1224
1144
  endpoint.searchParams.set("path", pathStr);
1225
1145
  }
1226
- endpoint.searchParams.set("key", (_e = options.apiKey) != null ? _e : config.apiKey);
1146
+ endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
1227
1147
  return endpoint.toString();
1228
1148
  }
1229
1149
  function bounded(boundingBox, options = {}) {
1230
- var _a, _b, _c, _d, _e;
1231
1150
  const style = styleToStyle(options.style);
1232
1151
  const scale = options.hiDPI ? "@2x" : "";
1233
- const format = (_a = options.format) != null ? _a : "png";
1234
- let width = ~~((_b = options.width) != null ? _b : 1024);
1235
- let height = ~~((_c = options.height) != null ? _c : 1024);
1152
+ const format = options.format ?? "png";
1153
+ let width = ~~(options.width ?? 1024);
1154
+ let height = ~~(options.height ?? 1024);
1236
1155
  if (options.hiDPI) {
1237
1156
  width = ~~(width / 2);
1238
1157
  height = ~~(height / 2);
@@ -1265,7 +1184,7 @@ function bounded(boundingBox, options = {}) {
1265
1184
  }
1266
1185
  if ("path" in options) {
1267
1186
  let pathStr = "";
1268
- pathStr += `fill:${(_d = options.pathFillColor) != null ? _d : "none"}|`;
1187
+ pathStr += `fill:${options.pathFillColor ?? "none"}|`;
1269
1188
  if ("pathStrokeColor" in options) {
1270
1189
  pathStr += `stroke:${options.pathStrokeColor}|`;
1271
1190
  }
@@ -1276,11 +1195,10 @@ function bounded(boundingBox, options = {}) {
1276
1195
  pathStr += simplifyAndStringify(options.path);
1277
1196
  endpoint.searchParams.set("path", pathStr);
1278
1197
  }
1279
- endpoint.searchParams.set("key", (_e = options.apiKey) != null ? _e : config.apiKey);
1198
+ endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
1280
1199
  return endpoint.toString();
1281
1200
  }
1282
1201
  function automatic(options = {}) {
1283
- var _a, _b, _c, _d, _e;
1284
1202
  if (!("markers" in options) && !("path" in options)) {
1285
1203
  throw new Error(
1286
1204
  "Automatic static maps require markers and/or path to be created."
@@ -1288,9 +1206,9 @@ function automatic(options = {}) {
1288
1206
  }
1289
1207
  const style = styleToStyle(options.style);
1290
1208
  const scale = options.hiDPI ? "@2x" : "";
1291
- const format = (_a = options.format) != null ? _a : "png";
1292
- let width = ~~((_b = options.width) != null ? _b : 1024);
1293
- let height = ~~((_c = options.height) != null ? _c : 1024);
1209
+ const format = options.format ?? "png";
1210
+ let width = ~~(options.width ?? 1024);
1211
+ let height = ~~(options.height ?? 1024);
1294
1212
  if (options.hiDPI) {
1295
1213
  width = ~~(width / 2);
1296
1214
  height = ~~(height / 2);
@@ -1325,7 +1243,7 @@ function automatic(options = {}) {
1325
1243
  }
1326
1244
  if ("path" in options) {
1327
1245
  let pathStr = "";
1328
- pathStr += `fill:${(_d = options.pathFillColor) != null ? _d : "none"}|`;
1246
+ pathStr += `fill:${options.pathFillColor ?? "none"}|`;
1329
1247
  if ("pathStrokeColor" in options) {
1330
1248
  pathStr += `stroke:${options.pathStrokeColor}|`;
1331
1249
  }
@@ -1336,7 +1254,7 @@ function automatic(options = {}) {
1336
1254
  pathStr += simplifyAndStringify(options.path);
1337
1255
  endpoint.searchParams.set("path", pathStr);
1338
1256
  }
1339
- endpoint.searchParams.set("key", (_e = options.apiKey) != null ? _e : config.apiKey);
1257
+ endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
1340
1258
  return endpoint.toString();
1341
1259
  }
1342
1260
  const staticMaps = {
@@ -1345,18 +1263,355 @@ const staticMaps = {
1345
1263
  automatic
1346
1264
  };
1347
1265
 
1266
+ const EARTH_RADIUS = 63710088e-1;
1267
+ const EARTH_CIRCUMFERENCE = 2 * Math.PI * EARTH_RADIUS;
1268
+ function longitudeToMercatorX(lng) {
1269
+ return (180 + lng) / 360;
1270
+ }
1271
+ function latitudeToMercatorY(lat) {
1272
+ return (180 - 180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360))) / 360;
1273
+ }
1274
+ function wgs84ToMercator(position) {
1275
+ const wrappedPos = wrapWgs84(position);
1276
+ return [
1277
+ longitudeToMercatorX(wrappedPos[0]),
1278
+ latitudeToMercatorY(wrappedPos[1])
1279
+ ];
1280
+ }
1281
+ function mercatorXToLongitude(x) {
1282
+ return x * 360 - 180;
1283
+ }
1284
+ function mercatorYToLatitude(y) {
1285
+ const y2 = 180 - y * 360;
1286
+ return 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90;
1287
+ }
1288
+ function mercatorToWgs84(position) {
1289
+ return [mercatorXToLongitude(position[0]), mercatorYToLatitude(position[1])];
1290
+ }
1291
+ function haversineDistanceWgs84(from, to) {
1292
+ const rad = Math.PI / 180;
1293
+ const lat1 = from[1] * rad;
1294
+ const lat2 = to[1] * rad;
1295
+ const a = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos((to[0] - from[0]) * rad);
1296
+ const maxMeters = EARTH_RADIUS * Math.acos(Math.min(a, 1));
1297
+ return maxMeters;
1298
+ }
1299
+ function haversineCumulatedDistanceWgs84(positions) {
1300
+ const cumulatedDistance = Array(positions.length);
1301
+ cumulatedDistance[0] = 0;
1302
+ const l = cumulatedDistance.length;
1303
+ for (let i = 1; i < l; i++) {
1304
+ cumulatedDistance[i] = haversineDistanceWgs84(positions[i - 1], positions[i]) + cumulatedDistance[i - 1];
1305
+ }
1306
+ return cumulatedDistance;
1307
+ }
1308
+ function wrapWgs84(position) {
1309
+ const lng = position[0];
1310
+ const lat = position[1];
1311
+ const d = 360;
1312
+ const w = ((lng + 180) % d + d) % d - 180;
1313
+ const wrapLong = w === -180 ? 180 : w;
1314
+ return [wrapLong, lat];
1315
+ }
1316
+ function circumferenceAtLatitude(latitude) {
1317
+ return EARTH_CIRCUMFERENCE * Math.cos(latitude * Math.PI / 180);
1318
+ }
1319
+ function mercatorToTileIndex(position, zoom, strict = true) {
1320
+ const numberOfTilePerAxis = 2 ** zoom;
1321
+ const fIndex = [
1322
+ position[0] * numberOfTilePerAxis,
1323
+ position[1] * numberOfTilePerAxis
1324
+ ];
1325
+ return strict ? [~~fIndex[0], ~~fIndex[1]] : fIndex;
1326
+ }
1327
+ function wgs84ToTileIndex(position, zoom, strict = true) {
1328
+ const merc = wgs84ToMercator(position);
1329
+ return mercatorToTileIndex(merc, zoom, strict);
1330
+ }
1331
+ function toRadians(degrees) {
1332
+ return degrees * Math.PI / 180;
1333
+ }
1334
+ function toDegrees(radians) {
1335
+ return radians * 180 / Math.PI;
1336
+ }
1337
+ function haversineIntermediateWgs84(pos1, pos2, ratio) {
1338
+ const d = haversineDistanceWgs84(pos1, pos2);
1339
+ const \u03BB1 = toRadians(pos1[0]);
1340
+ const \u03C61 = toRadians(pos1[1]);
1341
+ const \u03BB2 = toRadians(pos2[0]);
1342
+ const \u03C62 = toRadians(pos2[1]);
1343
+ const \u03B4 = d / EARTH_RADIUS;
1344
+ const a = Math.sin((1 - ratio) * \u03B4) / Math.sin(\u03B4);
1345
+ const b = Math.sin(ratio * \u03B4) / Math.sin(\u03B4);
1346
+ const x = a * Math.cos(\u03C61) * Math.cos(\u03BB1) + b * Math.cos(\u03C62) * Math.cos(\u03BB2);
1347
+ const y = a * Math.cos(\u03C61) * Math.sin(\u03BB1) + b * Math.cos(\u03C62) * Math.sin(\u03BB2);
1348
+ const z = a * Math.sin(\u03C61) + b * Math.sin(\u03C62);
1349
+ const \u03C63 = Math.atan2(z, Math.sqrt(x * x + y * y));
1350
+ const \u03BB3 = Math.atan2(y, x);
1351
+ return [toDegrees(\u03BB3), toDegrees(\u03C63)];
1352
+ }
1353
+ const math = {
1354
+ EARTH_RADIUS,
1355
+ EARTH_CIRCUMFERENCE,
1356
+ longitudeToMercatorX,
1357
+ latitudeToMercatorY,
1358
+ wgs84ToMercator,
1359
+ mercatorXToLongitude,
1360
+ mercatorYToLatitude,
1361
+ mercatorToWgs84,
1362
+ haversineDistanceWgs84,
1363
+ wrapWgs84,
1364
+ circumferenceAtLatitude,
1365
+ mercatorToTileIndex,
1366
+ wgs84ToTileIndex,
1367
+ toRadians,
1368
+ toDegrees,
1369
+ haversineIntermediateWgs84,
1370
+ haversineCumulatedDistanceWgs84
1371
+ };
1372
+
1373
+ let tileCache = null;
1374
+ function getTileCache() {
1375
+ if (!tileCache) {
1376
+ tileCache = new QuickLRU({ maxSize: config.tileCacheSize });
1377
+ }
1378
+ return tileCache;
1379
+ }
1380
+ async function bufferToPixelDataBrowser(buff) {
1381
+ const blob = new Blob([buff]);
1382
+ const imageBitmap = await createImageBitmap(blob);
1383
+ const canvas = document.createElement("canvas");
1384
+ const ctx = canvas.getContext("2d");
1385
+ canvas.width = imageBitmap.width;
1386
+ canvas.height = imageBitmap.height;
1387
+ ctx.drawImage(imageBitmap, 0, 0);
1388
+ const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
1389
+ return {
1390
+ pixels: imageData.data,
1391
+ width: canvas.width,
1392
+ height: canvas.height,
1393
+ components: imageData.data.length / (canvas.width * canvas.height)
1394
+ };
1395
+ }
1396
+ function getBufferToPixelDataParser() {
1397
+ if (config.bufferToPixelData) {
1398
+ return config.bufferToPixelData;
1399
+ }
1400
+ if (typeof window !== "undefined") {
1401
+ return bufferToPixelDataBrowser;
1402
+ }
1403
+ throw new Error(
1404
+ "An image file buffer to pixel data parser is necessary. Specify it in `config.bufferToPixelData`"
1405
+ );
1406
+ }
1407
+
1408
+ const terrainTileJsonURL = "tiles/terrain-rgb-v2/tiles.json";
1409
+ let terrainTileJson = null;
1410
+ const customMessages = {
1411
+ 403: "Key is missing, invalid or restricted"
1412
+ };
1413
+ async function fetchTerrainTileJson(apiKey) {
1414
+ const endpoint = new URL(terrainTileJsonURL, defaults.maptilerApiURL);
1415
+ endpoint.searchParams.set("key", apiKey);
1416
+ const urlWithParams = endpoint.toString();
1417
+ const res = await callFetch(urlWithParams);
1418
+ if (res.ok) {
1419
+ terrainTileJson = await res.json();
1420
+ return terrainTileJson;
1421
+ } else {
1422
+ if (!res.ok) {
1423
+ throw new ServiceError(res, customMessages[res.status] ?? "");
1424
+ }
1425
+ }
1426
+ }
1427
+ async function at(position, options = {}) {
1428
+ const apiKey = options.apiKey ?? config.apiKey;
1429
+ if (!terrainTileJson) {
1430
+ await fetchTerrainTileJson(apiKey);
1431
+ }
1432
+ const maxZoom = terrainTileJson.maxzoom;
1433
+ let zoom = ~~(options.zoom ?? maxZoom);
1434
+ if (zoom > maxZoom || zoom < 0) {
1435
+ zoom = maxZoom;
1436
+ }
1437
+ const tileIndex = math.wgs84ToTileIndex(position, zoom, false);
1438
+ const tileX = ~~tileIndex[0];
1439
+ const tileY = ~~tileIndex[1];
1440
+ if (!terrainTileJson.tiles.length) {
1441
+ throw new Error("Terrain tileJSON tile list is empty.");
1442
+ }
1443
+ const tileID = `terrain_${zoom.toString()}_${tileX.toString()}_${tileY.toString()}`;
1444
+ let tilePixelData;
1445
+ const cache = getTileCache();
1446
+ if (cache.has(tileID)) {
1447
+ tilePixelData = cache.get(tileID);
1448
+ } else {
1449
+ const tileURL = terrainTileJson.tiles[0].replace("{x}", tileX.toString()).replace("{y}", tileY.toString()).replace("{z}", zoom.toString());
1450
+ const tileRes = await callFetch(tileURL);
1451
+ if (!tileRes.ok) {
1452
+ throw new ServiceError(tileRes, customMessages[tileRes.status] ?? "");
1453
+ }
1454
+ const tileBuff = await tileRes.arrayBuffer();
1455
+ const tileParser = getBufferToPixelDataParser();
1456
+ tilePixelData = await tileParser(tileBuff);
1457
+ cache.set(tileID, tilePixelData);
1458
+ }
1459
+ const pixelX = ~~(tilePixelData.width * (tileIndex[0] % 1));
1460
+ const pixelY = ~~(tilePixelData.height * (tileIndex[1] % 1));
1461
+ const pixelDataIndex = (pixelY * tilePixelData.width + pixelX) * tilePixelData.components;
1462
+ const R = tilePixelData.pixels[pixelDataIndex];
1463
+ const G = tilePixelData.pixels[pixelDataIndex + 1];
1464
+ const B = tilePixelData.pixels[pixelDataIndex + 2];
1465
+ const elevation2 = -1e4 + (R * 256 * 256 + G * 256 + B) * 0.1;
1466
+ return [position[0], position[1], elevation2];
1467
+ }
1468
+ async function batch(positions, options = {}) {
1469
+ const apiKey = options.apiKey ?? config.apiKey;
1470
+ if (!terrainTileJson) {
1471
+ await fetchTerrainTileJson(apiKey);
1472
+ }
1473
+ const tileParser = getBufferToPixelDataParser();
1474
+ const tileURLSchema = terrainTileJson.tiles[0];
1475
+ const cache = getTileCache();
1476
+ const maxZoom = terrainTileJson.maxzoom;
1477
+ let zoom = ~~(options.zoom ?? maxZoom);
1478
+ if (zoom > maxZoom || zoom < 0) {
1479
+ zoom = maxZoom;
1480
+ }
1481
+ const tileIndicesFloats = positions.map(
1482
+ (position) => math.wgs84ToTileIndex(position, zoom, false)
1483
+ );
1484
+ const tileIndicesInteger = tileIndicesFloats.map((index) => [
1485
+ ~~index[0],
1486
+ ~~index[1]
1487
+ ]);
1488
+ const tileIDs = tileIndicesInteger.map(
1489
+ (index) => `terrain_${zoom.toString()}_${index[0].toString()}_${index[1].toString()}`
1490
+ );
1491
+ const uniqueTilesToFetch = Array.from(
1492
+ new Set(tileIDs.filter((tileID) => !cache.has(tileID)))
1493
+ ).map((tileID) => tileID.split("_").slice(1));
1494
+ const tileURLs = uniqueTilesToFetch.map(
1495
+ (zxy) => tileURLSchema.replace("{x}", zxy[1].toString()).replace("{y}", zxy[2].toString()).replace("{z}", zxy[0].toString())
1496
+ );
1497
+ const promisesFetchTiles = tileURLs.map((url) => callFetch(url));
1498
+ const resTiles = await Promise.allSettled(promisesFetchTiles);
1499
+ const fulfilledRes = resTiles.map(
1500
+ (el) => el.status === "fulfilled" ? el.value : null
1501
+ ).filter((res) => res);
1502
+ const fulfilledRButNotOkRes = fulfilledRes.filter((res) => !res.ok);
1503
+ if (fulfilledRes.length !== promisesFetchTiles.length) {
1504
+ throw new Error("Some tiles could not be fetched.");
1505
+ }
1506
+ if (fulfilledRButNotOkRes.length) {
1507
+ throw new ServiceError(
1508
+ fulfilledRButNotOkRes[0],
1509
+ customMessages[fulfilledRButNotOkRes[0].status] ?? ""
1510
+ );
1511
+ }
1512
+ const tileArrayBuffers = await Promise.all(
1513
+ fulfilledRes.map((res) => res.arrayBuffer())
1514
+ );
1515
+ if (!tileArrayBuffers.every((buff) => buff.byteLength > 0)) {
1516
+ throw new Error("Some tiles are not available.");
1517
+ }
1518
+ const tilePixelDatas = await Promise.all(
1519
+ tileArrayBuffers.map((buff) => tileParser(buff))
1520
+ );
1521
+ tilePixelDatas.forEach((tilePixelData, i) => {
1522
+ const zxy = uniqueTilesToFetch[i];
1523
+ const tileID = `terrain_${zxy[0].toString()}_${zxy[1].toString()}_${zxy[2].toString()}`;
1524
+ cache.set(tileID, tilePixelData);
1525
+ });
1526
+ const elevatedPositions = positions.map((position, i) => {
1527
+ const tileID = tileIDs[i];
1528
+ const tileIndexFloat = tileIndicesFloats[i];
1529
+ const tilePixelData = cache.get(tileID);
1530
+ const pixelX = Math.min(
1531
+ Math.round(tilePixelData.width * (tileIndexFloat[0] % 1)),
1532
+ tilePixelData.width - 1
1533
+ );
1534
+ const pixelY = Math.min(
1535
+ Math.round(tilePixelData.height * (tileIndexFloat[1] % 1)),
1536
+ tilePixelData.height - 1
1537
+ );
1538
+ const pixelDataIndex = (pixelY * tilePixelData.width + pixelX) * tilePixelData.components;
1539
+ const R = tilePixelData.pixels[pixelDataIndex];
1540
+ const G = tilePixelData.pixels[pixelDataIndex + 1];
1541
+ const B = tilePixelData.pixels[pixelDataIndex + 2];
1542
+ const elevation2 = -1e4 + (R * 256 * 256 + G * 256 + B) * 0.1;
1543
+ return [position[0], position[1], ~~(elevation2 * 1e3) / 1e3];
1544
+ });
1545
+ if (options.smoothingKernelSize) {
1546
+ const kernelSize = ~~(options.smoothingKernelSize / 2) * 2 + 1;
1547
+ const elevations = elevatedPositions.map((pos) => pos[2]);
1548
+ const kernelSpan = ~~(kernelSize / 2);
1549
+ for (let i = kernelSpan; i < elevations.length - kernelSpan - 1; i += 1) {
1550
+ let sum = 0;
1551
+ for (let j = 0; j < kernelSize; j += 1) {
1552
+ const elev = elevations[i - kernelSpan + j];
1553
+ sum += elev;
1554
+ }
1555
+ sum /= kernelSize;
1556
+ elevatedPositions[i][2] = sum;
1557
+ }
1558
+ }
1559
+ return elevatedPositions;
1560
+ }
1561
+ async function fromLineString(ls, options = {}) {
1562
+ if (ls.type !== "LineString") {
1563
+ throw new Error("The provided object is not a GeoJSON LineString");
1564
+ }
1565
+ const clone = structuredClone(ls);
1566
+ const elevatedPositions = await batch(clone.coordinates, options);
1567
+ clone.coordinates = elevatedPositions;
1568
+ return clone;
1569
+ }
1570
+ async function fromMultiLineString(ls, options = {}) {
1571
+ if (ls.type !== "MultiLineString") {
1572
+ throw new Error("The provided object is not a GeoJSON MultiLineString");
1573
+ }
1574
+ const clone = structuredClone(ls);
1575
+ const multiLengths = clone.coordinates.map((poss) => poss.length);
1576
+ const flattenPositions = clone.coordinates.flat();
1577
+ const flattenPositionsElevated = await batch(flattenPositions, options);
1578
+ const result = [];
1579
+ let index = 0;
1580
+ for (const length of multiLengths) {
1581
+ result.push(flattenPositionsElevated.slice(index, index + length));
1582
+ index += length;
1583
+ }
1584
+ clone.coordinates = result;
1585
+ return clone;
1586
+ }
1587
+ const elevation = {
1588
+ at,
1589
+ batch,
1590
+ fromLineString,
1591
+ fromMultiLineString
1592
+ };
1593
+
1348
1594
  exports.ClientConfig = ClientConfig;
1349
1595
  exports.LanguageGeocoding = LanguageGeocoding;
1350
1596
  exports.MapStyle = MapStyle;
1351
1597
  exports.MapStyleVariant = MapStyleVariant;
1352
1598
  exports.ReferenceMapStyle = ReferenceMapStyle;
1353
1599
  exports.ServiceError = ServiceError;
1600
+ exports.bufferToPixelDataBrowser = bufferToPixelDataBrowser;
1601
+ exports.circumferenceAtLatitude = circumferenceAtLatitude;
1354
1602
  exports.config = config;
1355
1603
  exports.coordinates = coordinates;
1356
1604
  exports.data = data;
1605
+ exports.elevation = elevation;
1357
1606
  exports.expandMapStyle = expandMapStyle;
1358
1607
  exports.geocoding = geocoding;
1359
1608
  exports.geolocation = geolocation;
1609
+ exports.getAutoLanguageGeocoding = getAutoLanguageGeocoding;
1610
+ exports.getBufferToPixelDataParser = getBufferToPixelDataParser;
1611
+ exports.getTileCache = getTileCache;
1360
1612
  exports.mapStylePresetList = mapStylePresetList;
1613
+ exports.math = math;
1614
+ exports.misc = misc;
1361
1615
  exports.staticMaps = staticMaps;
1616
+ exports.styleToStyle = styleToStyle;
1362
1617
  //# sourceMappingURL=maptiler-client.cjs.map