@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,4 +1,4 @@
1
- import { llToTile, llToTilePx } from 'web-merc-projection';
1
+ import QuickLRU from 'quick-lru';
2
2
 
3
3
  function tryGettingFetch() {
4
4
  if (typeof self !== "undefined") {
@@ -20,6 +20,10 @@ class ClientConfig {
20
20
  * will be automatically resolved.
21
21
  */
22
22
  this._fetch = tryGettingFetch();
23
+ /**
24
+ * Number of tiles to keep in cache
25
+ */
26
+ this.tileCacheSize = 200;
23
27
  }
24
28
  /**
25
29
  * Set the MapTiler Cloud API key
@@ -145,17 +149,18 @@ class ServiceError extends Error {
145
149
  }
146
150
  }
147
151
 
148
- const customMessages$3 = {
152
+ const customMessages$4 = {
149
153
  400: "Query too long / Invalid parameters",
150
154
  403: "Key is missing, invalid or restricted"
151
155
  };
152
156
  function addLanguageGeocodingOptions(searchParams, options) {
153
- if (options.language == void 0) {
157
+ const { language } = options;
158
+ if (language == void 0) {
154
159
  return;
155
160
  }
156
161
  const languages = Array.from(
157
162
  new Set(
158
- (Array.isArray(options.language) ? options.language : [options.language]).map(
163
+ (Array.isArray(language) ? language : [language]).map(
159
164
  (lang) => lang === LanguageGeocoding.AUTO ? getAutoLanguageGeocoding() : lang
160
165
  )
161
166
  )
@@ -163,31 +168,39 @@ function addLanguageGeocodingOptions(searchParams, options) {
163
168
  searchParams.set("language", languages);
164
169
  }
165
170
  function addCommonForwardAndReverseGeocodingOptions(searchParams, options) {
166
- searchParams.set("key", options.apiKey ?? config.apiKey);
167
- if (options.limit != void 0) {
168
- searchParams.set("limit", String(options.limit));
171
+ const { apiKey, limit, types, excludeTypes } = options;
172
+ searchParams.set("key", apiKey ?? config.apiKey);
173
+ if (limit != void 0) {
174
+ searchParams.set("limit", String(limit));
169
175
  }
170
- if (options.types != void 0) {
171
- searchParams.set("types", options.types.join(","));
176
+ if (types != void 0) {
177
+ searchParams.set("types", types.join(","));
178
+ }
179
+ if (excludeTypes != void 0) {
180
+ searchParams.set("excludeTypes", String(excludeTypes));
172
181
  }
173
182
  addLanguageGeocodingOptions(searchParams, options);
174
183
  }
175
184
  function addForwardGeocodingOptions(searchParams, options) {
176
185
  addCommonForwardAndReverseGeocodingOptions(searchParams, options);
177
- if (options.bbox != void 0) {
178
- searchParams.set("bbox", options.bbox.join(","));
179
- }
180
- if (options.proximity != void 0) {
181
- searchParams.set("proximity", options.proximity.join(","));
186
+ const { bbox, proximity, country, fuzzyMatch, autocomplete } = options;
187
+ if (bbox != void 0) {
188
+ searchParams.set("bbox", bbox.join(","));
189
+ }
190
+ if (proximity != void 0) {
191
+ searchParams.set(
192
+ "proximity",
193
+ proximity === "ip" ? proximity : proximity.join(",")
194
+ );
182
195
  }
183
- if (options.country != void 0) {
184
- searchParams.set("country", options.country.join(","));
196
+ if (country != void 0) {
197
+ searchParams.set("country", country.join(","));
185
198
  }
186
- if (options.fuzzyMatch != void 0) {
187
- searchParams.set("fuzzyMatch", options.fuzzyMatch ? "true" : "false");
199
+ if (fuzzyMatch != void 0) {
200
+ searchParams.set("fuzzyMatch", fuzzyMatch ? "true" : "false");
188
201
  }
189
- if (options.autocomplete != void 0) {
190
- searchParams.set("autocomplete", options.autocomplete ? "true" : "false");
202
+ if (autocomplete != void 0) {
203
+ searchParams.set("autocomplete", autocomplete ? "true" : "false");
191
204
  }
192
205
  }
193
206
  async function forward(query, options = {}) {
@@ -203,7 +216,7 @@ async function forward(query, options = {}) {
203
216
  const urlWithParams = endpoint.toString();
204
217
  const res = await callFetch(urlWithParams);
205
218
  if (!res.ok) {
206
- throw new ServiceError(res, customMessages$3[res.status] ?? "");
219
+ throw new ServiceError(res, customMessages$4[res.status] ?? "");
207
220
  }
208
221
  const obj = await res.json();
209
222
  return obj;
@@ -220,7 +233,7 @@ async function reverse(position, options = {}) {
220
233
  const urlWithParams = endpoint.toString();
221
234
  const res = await callFetch(urlWithParams);
222
235
  if (!res.ok) {
223
- throw new ServiceError(res, customMessages$3[res.status] ?? "");
236
+ throw new ServiceError(res, customMessages$4[res.status] ?? "");
224
237
  }
225
238
  const obj = await res.json();
226
239
  return obj;
@@ -232,12 +245,12 @@ async function byId(id, options = {}) {
232
245
  const urlWithParams = endpoint.toString();
233
246
  const res = await callFetch(urlWithParams);
234
247
  if (!res.ok) {
235
- throw new ServiceError(res, customMessages$3[res.status] ?? "");
248
+ throw new ServiceError(res, customMessages$4[res.status] ?? "");
236
249
  }
237
250
  const obj = await res.json();
238
251
  return obj;
239
252
  }
240
- async function batch(queries, options = {}) {
253
+ async function batch$1(queries, options = {}) {
241
254
  if (!queries.length) {
242
255
  return [];
243
256
  }
@@ -251,7 +264,7 @@ async function batch(queries, options = {}) {
251
264
  const urlWithParams = endpoint.toString();
252
265
  const res = await callFetch(urlWithParams);
253
266
  if (!res.ok) {
254
- throw new ServiceError(res, customMessages$3[res.status] ?? "");
267
+ throw new ServiceError(res, customMessages$4[res.status] ?? "");
255
268
  }
256
269
  const obj = await res.json();
257
270
  return queries.length === 1 ? [obj] : obj;
@@ -260,11 +273,11 @@ const geocoding = {
260
273
  forward,
261
274
  reverse,
262
275
  byId,
263
- batch,
276
+ batch: batch$1,
264
277
  language: LanguageGeocoding
265
278
  };
266
279
 
267
- const customMessages$2 = {
280
+ const customMessages$3 = {
268
281
  403: "Key is missing, invalid or restricted"
269
282
  };
270
283
  async function info(options = {}) {
@@ -275,7 +288,7 @@ async function info(options = {}) {
275
288
  if (!res.ok) {
276
289
  throw new ServiceError(
277
290
  res,
278
- res.status in customMessages$2 ? customMessages$2[res.status] : ""
291
+ res.status in customMessages$3 ? customMessages$3[res.status] : ""
279
292
  );
280
293
  }
281
294
  const obj = await res.json();
@@ -285,7 +298,7 @@ const geolocation = {
285
298
  info
286
299
  };
287
300
 
288
- const customMessages$1 = {
301
+ const customMessages$2 = {
289
302
  403: "Key is missing, invalid or restricted"
290
303
  };
291
304
  async function search(query, options = {}) {
@@ -314,7 +327,7 @@ async function search(query, options = {}) {
314
327
  if (!res.ok) {
315
328
  throw new ServiceError(
316
329
  res,
317
- res.status in customMessages$1 ? customMessages$1[res.status] : ""
330
+ res.status in customMessages$2 ? customMessages$2[res.status] : ""
318
331
  );
319
332
  }
320
333
  const obj = await res.json();
@@ -344,7 +357,7 @@ async function transform(positions, options = {}) {
344
357
  if (!res.ok) {
345
358
  throw new ServiceError(
346
359
  res,
347
- res.status in customMessages$1 ? customMessages$1[res.status] : ""
360
+ res.status in customMessages$2 ? customMessages$2[res.status] : ""
348
361
  );
349
362
  }
350
363
  const obj = await res.json();
@@ -355,7 +368,7 @@ const coordinates = {
355
368
  transform
356
369
  };
357
370
 
358
- const customMessages = {
371
+ const customMessages$1 = {
359
372
  403: "Key is missing, invalid or restricted"
360
373
  };
361
374
  async function get(dataId, options = {}) {
@@ -372,7 +385,7 @@ async function get(dataId, options = {}) {
372
385
  if (!res.ok) {
373
386
  throw new ServiceError(
374
387
  res,
375
- res.status in customMessages ? customMessages[res.status] : ""
388
+ res.status in customMessages$1 ? customMessages$1[res.status] : ""
376
389
  );
377
390
  }
378
391
  const obj = await res.json();
@@ -979,6 +992,36 @@ function styleToStyle(style) {
979
992
  }
980
993
  const MapStyle = buildMapStyles();
981
994
 
995
+ function extractLineStrings(geoJson) {
996
+ const lineStrings = [];
997
+ function extractFromGeometry(geometry) {
998
+ if (geometry.type === "LineString" || geometry.type === "MultiLineString") {
999
+ lineStrings.push(geometry);
1000
+ }
1001
+ }
1002
+ function extractFromFeature(feature) {
1003
+ if (feature.geometry) {
1004
+ extractFromGeometry(feature.geometry);
1005
+ }
1006
+ }
1007
+ function extractFromFeatureCollection(collection) {
1008
+ for (const feature of collection.features) {
1009
+ if (feature.type === "Feature") {
1010
+ extractFromFeature(feature);
1011
+ } else if (feature.type === "FeatureCollection") {
1012
+ extractFromFeatureCollection(feature);
1013
+ }
1014
+ }
1015
+ }
1016
+ if (geoJson.type === "Feature") {
1017
+ extractFromFeature(geoJson);
1018
+ } else if (geoJson.type === "FeatureCollection") {
1019
+ extractFromFeatureCollection(geoJson);
1020
+ } else {
1021
+ extractFromGeometry(geoJson);
1022
+ }
1023
+ return lineStrings;
1024
+ }
982
1025
  function getSqSegDist(p, p1, p2) {
983
1026
  let x = p1[0], y = p1[1], dx = p2[0] - x, dy = p2[1] - y;
984
1027
  if (dx !== 0 || dy !== 0) {
@@ -1029,6 +1072,10 @@ function simplify(points, tolerance) {
1029
1072
  const simplePoints = simplifyDouglasPeucker(points, sqTolerance);
1030
1073
  return simplePoints;
1031
1074
  }
1075
+ const misc = {
1076
+ extractLineStrings,
1077
+ simplify
1078
+ };
1032
1079
 
1033
1080
  function staticMapMarkerToString(marker, includeColor = true) {
1034
1081
  let str = `${marker[0]},${marker[1]}`;
@@ -1042,7 +1089,7 @@ function simplifyAndStringify(path, maxNbChar = 3e3) {
1042
1089
  let tolerance = 5e-6;
1043
1090
  const toleranceStep = 1e-5;
1044
1091
  while (str.length > maxNbChar) {
1045
- const simplerPath = simplify(path, tolerance);
1092
+ const simplerPath = misc.simplify(path, tolerance);
1046
1093
  str = simplerPath.map((point) => `${point[0]},${point[1]}`).join("|");
1047
1094
  tolerance += toleranceStep;
1048
1095
  }
@@ -1214,294 +1261,333 @@ const staticMaps = {
1214
1261
  automatic
1215
1262
  };
1216
1263
 
1217
- const earthRadius = 63710088e-1;
1218
- function mToFt(m) {
1219
- return m * 3.28084;
1264
+ const EARTH_RADIUS = 63710088e-1;
1265
+ const EARTH_CIRCUMFERENCE = 2 * Math.PI * EARTH_RADIUS;
1266
+ function longitudeToMercatorX(lng) {
1267
+ return (180 + lng) / 360;
1220
1268
  }
1221
- function degToRad(degrees) {
1222
- return degrees % 360 * Math.PI / 180;
1269
+ function latitudeToMercatorY(lat) {
1270
+ return (180 - 180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360))) / 360;
1223
1271
  }
1224
- function radToDeg(radians) {
1225
- return radians * 180 / Math.PI;
1272
+ function wgs84ToMercator(position) {
1273
+ const wrappedPos = wrapWgs84(position);
1274
+ return [
1275
+ longitudeToMercatorX(wrappedPos[0]),
1276
+ latitudeToMercatorY(wrappedPos[1])
1277
+ ];
1278
+ }
1279
+ function mercatorXToLongitude(x) {
1280
+ return x * 360 - 180;
1281
+ }
1282
+ function mercatorYToLatitude(y) {
1283
+ const y2 = 180 - y * 360;
1284
+ return 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90;
1285
+ }
1286
+ function mercatorToWgs84(position) {
1287
+ return [mercatorXToLongitude(position[0]), mercatorYToLatitude(position[1])];
1226
1288
  }
1227
- function getZoomLevelResolution(latitude, zoom, tileSize = 512) {
1228
- return Math.cos(latitude * Math.PI / 180) * 2 * Math.PI * 6378137 / (tileSize * 2 ** zoom) * 3;
1289
+ function haversineDistanceWgs84(from, to) {
1290
+ const rad = Math.PI / 180;
1291
+ const lat1 = from[1] * rad;
1292
+ const lat2 = to[1] * rad;
1293
+ const a = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos((to[0] - from[0]) * rad);
1294
+ const maxMeters = EARTH_RADIUS * Math.acos(Math.min(a, 1));
1295
+ return maxMeters;
1229
1296
  }
1230
- function xyzToTileID(x, y, zoom) {
1231
- return ((1 << zoom) * y + x) * 32 + zoom;
1297
+ function haversineCumulatedDistanceWgs84(positions) {
1298
+ const cumulatedDistance = Array(positions.length);
1299
+ cumulatedDistance[0] = 0;
1300
+ const l = cumulatedDistance.length;
1301
+ for (let i = 1; i < l; i++) {
1302
+ cumulatedDistance[i] = haversineDistanceWgs84(positions[i - 1], positions[i]) + cumulatedDistance[i - 1];
1303
+ }
1304
+ return cumulatedDistance;
1232
1305
  }
1306
+ function wrapWgs84(position) {
1307
+ const lng = position[0];
1308
+ const lat = position[1];
1309
+ const d = 360;
1310
+ const w = ((lng + 180) % d + d) % d - 180;
1311
+ const wrapLong = w === -180 ? 180 : w;
1312
+ return [wrapLong, lat];
1313
+ }
1314
+ function circumferenceAtLatitude(latitude) {
1315
+ return EARTH_CIRCUMFERENCE * Math.cos(latitude * Math.PI / 180);
1316
+ }
1317
+ function mercatorToTileIndex(position, zoom, strict = true) {
1318
+ const numberOfTilePerAxis = 2 ** zoom;
1319
+ const fIndex = [
1320
+ position[0] * numberOfTilePerAxis,
1321
+ position[1] * numberOfTilePerAxis
1322
+ ];
1323
+ return strict ? [~~fIndex[0], ~~fIndex[1]] : fIndex;
1324
+ }
1325
+ function wgs84ToTileIndex(position, zoom, strict = true) {
1326
+ const merc = wgs84ToMercator(position);
1327
+ return mercatorToTileIndex(merc, zoom, strict);
1328
+ }
1329
+ function toRadians(degrees) {
1330
+ return degrees * Math.PI / 180;
1331
+ }
1332
+ function toDegrees(radians) {
1333
+ return radians * 180 / Math.PI;
1334
+ }
1335
+ function haversineIntermediateWgs84(pos1, pos2, ratio) {
1336
+ const d = haversineDistanceWgs84(pos1, pos2);
1337
+ const \u03BB1 = toRadians(pos1[0]);
1338
+ const \u03C61 = toRadians(pos1[1]);
1339
+ const \u03BB2 = toRadians(pos2[0]);
1340
+ const \u03C62 = toRadians(pos2[1]);
1341
+ const \u03B4 = d / EARTH_RADIUS;
1342
+ const a = Math.sin((1 - ratio) * \u03B4) / Math.sin(\u03B4);
1343
+ const b = Math.sin(ratio * \u03B4) / Math.sin(\u03B4);
1344
+ const x = a * Math.cos(\u03C61) * Math.cos(\u03BB1) + b * Math.cos(\u03C62) * Math.cos(\u03BB2);
1345
+ const y = a * Math.cos(\u03C61) * Math.sin(\u03BB1) + b * Math.cos(\u03C62) * Math.sin(\u03BB2);
1346
+ const z = a * Math.sin(\u03C61) + b * Math.sin(\u03C62);
1347
+ const \u03C63 = Math.atan2(z, Math.sqrt(x * x + y * y));
1348
+ const \u03BB3 = Math.atan2(y, x);
1349
+ return [toDegrees(\u03BB3), toDegrees(\u03C63)];
1350
+ }
1351
+ const math = {
1352
+ EARTH_RADIUS,
1353
+ EARTH_CIRCUMFERENCE,
1354
+ longitudeToMercatorX,
1355
+ latitudeToMercatorY,
1356
+ wgs84ToMercator,
1357
+ mercatorXToLongitude,
1358
+ mercatorYToLatitude,
1359
+ mercatorToWgs84,
1360
+ haversineDistanceWgs84,
1361
+ wrapWgs84,
1362
+ circumferenceAtLatitude,
1363
+ mercatorToTileIndex,
1364
+ wgs84ToTileIndex,
1365
+ toRadians,
1366
+ toDegrees,
1367
+ haversineIntermediateWgs84,
1368
+ haversineCumulatedDistanceWgs84
1369
+ };
1233
1370
 
1234
- function area(area2) {
1235
- const geometry = "geometry" in area2 ? area2.geometry : area2;
1236
- const type = geometry.type;
1237
- if (type === "MultiPolygon") {
1238
- return multiPolygonArea(geometry.coordinates);
1371
+ let tileCache = null;
1372
+ function getTileCache() {
1373
+ if (!tileCache) {
1374
+ tileCache = new QuickLRU({ maxSize: config.tileCacheSize });
1239
1375
  }
1240
- return polygonArea(geometry.coordinates);
1376
+ return tileCache;
1241
1377
  }
1242
- function multiPolygonArea(multiPoly) {
1243
- const coords = "coordinates" in multiPoly ? multiPoly.coordinates : multiPoly;
1244
- let total = 0;
1245
- for (const polygon of coords) {
1246
- total += polygonArea(polygon);
1247
- }
1248
- return total;
1378
+ async function bufferToPixelDataBrowser(buff) {
1379
+ const blob = new Blob([buff]);
1380
+ const imageBitmap = await createImageBitmap(blob);
1381
+ const canvas = document.createElement("canvas");
1382
+ const ctx = canvas.getContext("2d");
1383
+ canvas.width = imageBitmap.width;
1384
+ canvas.height = imageBitmap.height;
1385
+ ctx.drawImage(imageBitmap, 0, 0);
1386
+ const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
1387
+ return {
1388
+ pixels: imageData.data,
1389
+ width: canvas.width,
1390
+ height: canvas.height,
1391
+ components: imageData.data.length / (canvas.width * canvas.height)
1392
+ };
1249
1393
  }
1250
- function polygonArea(poly) {
1251
- const coords = "coordinates" in poly ? poly.coordinates : poly;
1252
- let total = 0;
1253
- for (const ring of coords) {
1254
- total += ringArea(ring);
1394
+ function getBufferToPixelDataParser() {
1395
+ if (config.bufferToPixelData) {
1396
+ return config.bufferToPixelData;
1255
1397
  }
1256
- return total;
1257
- }
1258
- function ringArea(coords) {
1259
- let p1;
1260
- let p2;
1261
- let p3;
1262
- let lowerIndex;
1263
- let middleIndex;
1264
- let upperIndex;
1265
- let i;
1266
- let total = 0;
1267
- const coordsLength = coords.length;
1268
- if (coordsLength > 2) {
1269
- for (i = 0; i < coordsLength; i++) {
1270
- if (i === coordsLength - 2) {
1271
- lowerIndex = coordsLength - 2;
1272
- middleIndex = coordsLength - 1;
1273
- upperIndex = 0;
1274
- } else if (i === coordsLength - 1) {
1275
- lowerIndex = coordsLength - 1;
1276
- middleIndex = 0;
1277
- upperIndex = 1;
1278
- } else {
1279
- lowerIndex = i;
1280
- middleIndex = i + 1;
1281
- upperIndex = i + 2;
1282
- }
1283
- p1 = coords[lowerIndex];
1284
- p2 = coords[middleIndex];
1285
- p3 = coords[upperIndex];
1286
- total += (degToRad(p3[0]) - degToRad(p1[0])) * Math.sin(degToRad(p2[1]));
1287
- }
1288
- total = total * earthRadius * earthRadius / 2;
1398
+ if (typeof window !== "undefined") {
1399
+ return bufferToPixelDataBrowser;
1289
1400
  }
1290
- return Math.abs(total);
1401
+ throw new Error(
1402
+ "An image file buffer to pixel data parser is necessary. Specify it in `config.bufferToPixelData`"
1403
+ );
1291
1404
  }
1292
1405
 
1293
- function lineDistance(line) {
1294
- const coordinates = "geometry" in line ? line.geometry.coordinates : "coordinates" in line ? line.coordinates : line;
1295
- let distance = 0;
1296
- let prevCoord;
1297
- for (const coordinate of coordinates) {
1298
- if (prevCoord !== void 0) {
1299
- distance += pointDistance(prevCoord, coordinate);
1406
+ const terrainTileJsonURL = "tiles/terrain-rgb-v2/tiles.json";
1407
+ let terrainTileJson = null;
1408
+ const customMessages = {
1409
+ 403: "Key is missing, invalid or restricted"
1410
+ };
1411
+ async function fetchTerrainTileJson(apiKey) {
1412
+ const endpoint = new URL(terrainTileJsonURL, defaults.maptilerApiURL);
1413
+ endpoint.searchParams.set("key", apiKey);
1414
+ const urlWithParams = endpoint.toString();
1415
+ const res = await callFetch(urlWithParams);
1416
+ if (res.ok) {
1417
+ terrainTileJson = await res.json();
1418
+ return terrainTileJson;
1419
+ } else {
1420
+ if (!res.ok) {
1421
+ throw new ServiceError(res, customMessages[res.status] ?? "");
1300
1422
  }
1301
- prevCoord = coordinate;
1302
1423
  }
1303
- return distance;
1304
1424
  }
1305
- function pointDistance(from, to) {
1306
- const { pow, sin, cos, sqrt, atan2 } = Math;
1307
- const dLat = degToRad(to[1] - from[1]);
1308
- const dLon = degToRad(to[0] - from[0]);
1309
- const lat1 = degToRad(from[1]);
1310
- const lat2 = degToRad(to[1]);
1311
- const a = pow(sin(dLat / 2), 2) + pow(sin(dLon / 2), 2) * cos(lat1) * cos(lat2);
1312
- return 2 * atan2(sqrt(a), sqrt(1 - a)) * earthRadius;
1313
- }
1314
-
1315
- function tileCover(coordinates, zoom, tileSize) {
1316
- const tileHash = /* @__PURE__ */ new Map();
1317
- const tiles = [];
1318
- const coords = [];
1319
- const resolution = getZoomLevelResolution(coordinates[0][1], zoom, tileSize);
1320
- const samples = sampleProfileLine(coordinates, resolution);
1321
- for (const sample of samples) {
1322
- const coordinate = sample;
1323
- const [tileX, tileY] = llToTile(coordinate, zoom, tileSize);
1324
- const id = xyzToTileID(tileX, tileY, zoom);
1325
- const tile = { id, x: tileX, y: tileY, z: zoom };
1326
- tileHash.set(id, tile);
1327
- coords.push({ coordinate, tile });
1328
- }
1329
- for (const tile of tileHash.values())
1330
- tiles.push(tile);
1331
- return { coords, tiles };
1332
- }
1333
- function sampleProfileLine(coordinates, resolution) {
1334
- const samples = [];
1335
- let prevCoord;
1336
- for (const coord of coordinates) {
1337
- if (prevCoord !== void 0) {
1338
- const dist = pointDistance(
1339
- prevCoord,
1340
- coord
1341
- );
1342
- const numSamples = Math.ceil(dist / resolution);
1343
- for (let i = 0; i <= numSamples - 1; i++) {
1344
- const sample = [
1345
- prevCoord[0] + (coord[0] - prevCoord[0]) * (i / numSamples),
1346
- prevCoord[1] + (coord[1] - prevCoord[1]) * (i / numSamples)
1347
- ];
1348
- samples.push(sample);
1349
- }
1350
- } else {
1351
- samples.push(coord);
1425
+ async function at(position, options = {}) {
1426
+ const apiKey = options.apiKey ?? config.apiKey;
1427
+ if (!terrainTileJson) {
1428
+ await fetchTerrainTileJson(apiKey);
1429
+ }
1430
+ const maxZoom = terrainTileJson.maxzoom;
1431
+ let zoom = ~~(options.zoom ?? maxZoom);
1432
+ if (zoom > maxZoom || zoom < 0) {
1433
+ zoom = maxZoom;
1434
+ }
1435
+ const tileIndex = math.wgs84ToTileIndex(position, zoom, false);
1436
+ const tileX = ~~tileIndex[0];
1437
+ const tileY = ~~tileIndex[1];
1438
+ if (!terrainTileJson.tiles.length) {
1439
+ throw new Error("Terrain tileJSON tile list is empty.");
1440
+ }
1441
+ const tileID = `terrain_${zoom.toString()}_${tileX.toString()}_${tileY.toString()}`;
1442
+ let tilePixelData;
1443
+ const cache = getTileCache();
1444
+ if (cache.has(tileID)) {
1445
+ tilePixelData = cache.get(tileID);
1446
+ } else {
1447
+ const tileURL = terrainTileJson.tiles[0].replace("{x}", tileX.toString()).replace("{y}", tileY.toString()).replace("{z}", zoom.toString());
1448
+ const tileRes = await callFetch(tileURL);
1449
+ if (!tileRes.ok) {
1450
+ throw new ServiceError(tileRes, customMessages[tileRes.status] ?? "");
1352
1451
  }
1353
- prevCoord = coord;
1354
- }
1355
- return samples;
1452
+ const tileBuff = await tileRes.arrayBuffer();
1453
+ const tileParser = getBufferToPixelDataParser();
1454
+ tilePixelData = await tileParser(tileBuff);
1455
+ cache.set(tileID, tilePixelData);
1456
+ }
1457
+ const pixelX = ~~(tilePixelData.width * (tileIndex[0] % 1));
1458
+ const pixelY = ~~(tilePixelData.height * (tileIndex[1] % 1));
1459
+ const pixelDataIndex = (pixelY * tilePixelData.width + pixelX) * tilePixelData.components;
1460
+ const R = tilePixelData.pixels[pixelDataIndex];
1461
+ const G = tilePixelData.pixels[pixelDataIndex + 1];
1462
+ const B = tilePixelData.pixels[pixelDataIndex + 2];
1463
+ const elevation2 = -1e4 + (R * 256 * 256 + G * 256 + B) * 0.1;
1464
+ return [position[0], position[1], elevation2];
1356
1465
  }
1357
-
1358
- function getElevation(coord, tile, tileSize, tileImage, elevationParser = defaultElevationParser) {
1359
- const { channels, image } = tileImage;
1360
- let [x, y] = llToTilePx(coord, tile, tileSize);
1361
- x = clampPixel(x, tileSize);
1362
- y = clampPixel(y, tileSize);
1363
- const index = (y * tileSize + x) * channels;
1364
- return elevationParser(
1365
- image[index],
1366
- image[index + 1],
1367
- image[index + 2],
1368
- channels === 4 ? image[index + 3] : 0
1466
+ async function batch(positions, options = {}) {
1467
+ const apiKey = options.apiKey ?? config.apiKey;
1468
+ if (!terrainTileJson) {
1469
+ await fetchTerrainTileJson(apiKey);
1470
+ }
1471
+ const tileParser = getBufferToPixelDataParser();
1472
+ const tileURLSchema = terrainTileJson.tiles[0];
1473
+ const cache = getTileCache();
1474
+ const maxZoom = terrainTileJson.maxzoom;
1475
+ let zoom = ~~(options.zoom ?? maxZoom);
1476
+ if (zoom > maxZoom || zoom < 0) {
1477
+ zoom = maxZoom;
1478
+ }
1479
+ const tileIndicesFloats = positions.map(
1480
+ (position) => math.wgs84ToTileIndex(position, zoom, false)
1369
1481
  );
1370
- }
1371
- function clampPixel(n, tileSize) {
1372
- return Math.max(0, Math.min(tileSize, Math.floor(n * tileSize)));
1373
- }
1374
- function defaultElevationParser(r, g, b) {
1375
- return -1e4 + (r * 256 * 256 + g * 256 + b) * 0.1;
1376
- }
1377
-
1378
- async function profileLineString(path, options) {
1379
- const coordinates = "geometry" in path ? path.geometry.coordinates : path.coordinates;
1380
- const { coords, tiles } = tileCover(
1381
- coordinates,
1382
- options.zoom ?? 13,
1383
- options.tileSize ?? 512
1482
+ const tileIndicesInteger = tileIndicesFloats.map((index) => [
1483
+ ~~index[0],
1484
+ ~~index[1]
1485
+ ]);
1486
+ const tileIDs = tileIndicesInteger.map(
1487
+ (index) => `terrain_${zoom.toString()}_${index[0].toString()}_${index[1].toString()}`
1384
1488
  );
1385
- const tileCache = await getTiles(tiles, options.tileRequest);
1386
- let points = getElevations(
1387
- coords,
1388
- tileCache,
1389
- options.tileSize ?? 512,
1390
- options.elevationParser
1489
+ const uniqueTilesToFetch = Array.from(
1490
+ new Set(tileIDs.filter((tileID) => !cache.has(tileID)))
1491
+ ).map((tileID) => tileID.split("_").slice(1));
1492
+ const tileURLs = uniqueTilesToFetch.map(
1493
+ (zxy) => tileURLSchema.replace("{x}", zxy[1].toString()).replace("{y}", zxy[2].toString()).replace("{z}", zxy[0].toString())
1391
1494
  );
1392
- if (options.smooth === true)
1393
- points = smoothElevation(points);
1394
- let output = buildOutput(points);
1395
- if (options.metric === "ft")
1396
- output = toFeet(output);
1397
- return output;
1398
- }
1399
- async function getTiles(tiles, tileRequest) {
1400
- const tileCache = /* @__PURE__ */ new Map();
1401
- const requests = [];
1402
- for (const tile of tiles) {
1403
- requests.push(
1404
- tileRequest(tile.x, tile.y, tile.z).then((res) => {
1405
- tileCache.set(tile.id, res);
1406
- return res;
1407
- }).catch((err) => {
1408
- console.error(err);
1409
- return void 0;
1410
- })
1495
+ const promisesFetchTiles = tileURLs.map((url) => callFetch(url));
1496
+ const resTiles = await Promise.allSettled(promisesFetchTiles);
1497
+ const fulfilledRes = resTiles.map(
1498
+ (el) => el.status === "fulfilled" ? el.value : null
1499
+ ).filter((res) => res);
1500
+ const fulfilledRButNotOkRes = fulfilledRes.filter((res) => !res.ok);
1501
+ if (fulfilledRes.length !== promisesFetchTiles.length) {
1502
+ throw new Error("Some tiles could not be fetched.");
1503
+ }
1504
+ if (fulfilledRButNotOkRes.length) {
1505
+ throw new ServiceError(
1506
+ fulfilledRButNotOkRes[0],
1507
+ customMessages[fulfilledRButNotOkRes[0].status] ?? ""
1411
1508
  );
1412
1509
  }
1413
- await Promise.allSettled(requests);
1414
- return tileCache;
1415
- }
1416
- function getElevations(coords, tileCache, tileSize, elevationParser) {
1417
- const points = [];
1418
- let curDistance = 0;
1419
- let prevCoord;
1420
- for (const { tile, coordinate } of coords) {
1421
- const cTile = tileCache.get(tile.id);
1422
- if (cTile === void 0)
1423
- throw new Error(
1424
- `Missing tile ${tile.id} (${tile.x}-${tile.y}-${tile.z})`
1425
- );
1426
- const elevation = getElevation(
1427
- coordinate,
1428
- [tile.z, tile.x, tile.y],
1429
- tileSize,
1430
- cTile,
1431
- elevationParser
1510
+ const tileArrayBuffers = await Promise.all(
1511
+ fulfilledRes.map((res) => res.arrayBuffer())
1512
+ );
1513
+ if (!tileArrayBuffers.every((buff) => buff.byteLength > 0)) {
1514
+ throw new Error("Some tiles are not available.");
1515
+ }
1516
+ const tilePixelDatas = await Promise.all(
1517
+ tileArrayBuffers.map((buff) => tileParser(buff))
1518
+ );
1519
+ tilePixelDatas.forEach((tilePixelData, i) => {
1520
+ const zxy = uniqueTilesToFetch[i];
1521
+ const tileID = `terrain_${zxy[0].toString()}_${zxy[1].toString()}_${zxy[2].toString()}`;
1522
+ cache.set(tileID, tilePixelData);
1523
+ });
1524
+ const elevatedPositions = positions.map((position, i) => {
1525
+ const tileID = tileIDs[i];
1526
+ const tileIndexFloat = tileIndicesFloats[i];
1527
+ const tilePixelData = cache.get(tileID);
1528
+ const pixelX = Math.min(
1529
+ Math.round(tilePixelData.width * (tileIndexFloat[0] % 1)),
1530
+ tilePixelData.width - 1
1531
+ );
1532
+ const pixelY = Math.min(
1533
+ Math.round(tilePixelData.height * (tileIndexFloat[1] % 1)),
1534
+ tilePixelData.height - 1
1432
1535
  );
1433
- points.push({
1434
- distance: curDistance,
1435
- elevation,
1436
- coordinate,
1437
- tile
1438
- });
1439
- if (prevCoord !== void 0) {
1440
- curDistance += pointDistance(prevCoord, coordinate);
1536
+ const pixelDataIndex = (pixelY * tilePixelData.width + pixelX) * tilePixelData.components;
1537
+ const R = tilePixelData.pixels[pixelDataIndex];
1538
+ const G = tilePixelData.pixels[pixelDataIndex + 1];
1539
+ const B = tilePixelData.pixels[pixelDataIndex + 2];
1540
+ const elevation2 = -1e4 + (R * 256 * 256 + G * 256 + B) * 0.1;
1541
+ return [position[0], position[1], ~~(elevation2 * 1e3) / 1e3];
1542
+ });
1543
+ if (options.smoothingKernelSize) {
1544
+ const kernelSize = ~~(options.smoothingKernelSize / 2) * 2 + 1;
1545
+ const elevations = elevatedPositions.map((pos) => pos[2]);
1546
+ const kernelSpan = ~~(kernelSize / 2);
1547
+ for (let i = kernelSpan; i < elevations.length - kernelSpan - 1; i += 1) {
1548
+ let sum = 0;
1549
+ for (let j = 0; j < kernelSize; j += 1) {
1550
+ const elev = elevations[i - kernelSpan + j];
1551
+ sum += elev;
1552
+ }
1553
+ sum /= kernelSize;
1554
+ elevatedPositions[i][2] = sum;
1441
1555
  }
1442
- prevCoord = coordinate;
1443
1556
  }
1444
- return points;
1557
+ return elevatedPositions;
1445
1558
  }
1446
- function buildOutput(points) {
1447
- let minElevation = Infinity;
1448
- let maxElevation = -Infinity;
1449
- let totalElevation = 0;
1450
- for (const point of points) {
1451
- if (point.elevation < minElevation)
1452
- minElevation = point.elevation;
1453
- if (point.elevation > maxElevation)
1454
- maxElevation = point.elevation;
1455
- totalElevation += point.elevation;
1456
- }
1457
- return {
1458
- distance: points[points.length - 1].distance,
1459
- minElevation,
1460
- maxElevation,
1461
- avgElevation: totalElevation / points.length,
1462
- startElevation: points[0].elevation,
1463
- endElevation: points[points.length - 1].elevation,
1464
- points
1465
- };
1559
+ async function fromLineString(ls, options = {}) {
1560
+ if (ls.type !== "LineString") {
1561
+ throw new Error("The provided object is not a GeoJSON LineString");
1562
+ }
1563
+ const clone = structuredClone(ls);
1564
+ const elevatedPositions = await batch(clone.coordinates, options);
1565
+ clone.coordinates = elevatedPositions;
1566
+ return clone;
1466
1567
  }
1467
- function smoothElevation(points) {
1468
- const newPoints = [];
1469
- let prevPoint;
1470
- for (let i = 0; i < points.length; i++) {
1471
- const point = points[i];
1472
- const nextPoint = points[i + 1] ?? points[i];
1473
- if (prevPoint === void 0) {
1474
- newPoints.push(point);
1475
- } else {
1476
- const newPoint = {
1477
- distance: point.distance,
1478
- elevation: (prevPoint.elevation + point.elevation + nextPoint.elevation) / 3,
1479
- coordinate: point.coordinate,
1480
- tile: point.tile
1481
- };
1482
- newPoints.push(newPoint);
1483
- }
1484
- prevPoint = point;
1485
- }
1486
- return newPoints;
1487
- }
1488
- function toFeet(input) {
1489
- const output = {
1490
- distance: mToFt(input.distance),
1491
- minElevation: mToFt(input.minElevation),
1492
- maxElevation: mToFt(input.maxElevation),
1493
- avgElevation: mToFt(input.avgElevation),
1494
- startElevation: mToFt(input.startElevation),
1495
- endElevation: mToFt(input.endElevation),
1496
- points: input.points.map(({ distance, elevation, coordinate, tile }) => ({
1497
- distance: mToFt(distance),
1498
- elevation: mToFt(elevation),
1499
- coordinate,
1500
- tile
1501
- }))
1502
- };
1503
- return output;
1568
+ async function fromMultiLineString(ls, options = {}) {
1569
+ if (ls.type !== "MultiLineString") {
1570
+ throw new Error("The provided object is not a GeoJSON MultiLineString");
1571
+ }
1572
+ const clone = structuredClone(ls);
1573
+ const multiLengths = clone.coordinates.map((poss) => poss.length);
1574
+ const flattenPositions = clone.coordinates.flat();
1575
+ const flattenPositionsElevated = await batch(flattenPositions, options);
1576
+ const result = [];
1577
+ let index = 0;
1578
+ for (const length of multiLengths) {
1579
+ result.push(flattenPositionsElevated.slice(index, index + length));
1580
+ index += length;
1581
+ }
1582
+ clone.coordinates = result;
1583
+ return clone;
1504
1584
  }
1585
+ const elevation = {
1586
+ at,
1587
+ batch,
1588
+ fromLineString,
1589
+ fromMultiLineString
1590
+ };
1505
1591
 
1506
- export { ClientConfig, LanguageGeocoding, MapStyle, MapStyleVariant, ReferenceMapStyle, ServiceError, area, config, coordinates, data, defaultElevationParser, degToRad, earthRadius, expandMapStyle, geocoding, geolocation, getZoomLevelResolution, lineDistance, mToFt, mapStylePresetList, multiPolygonArea, pointDistance, polygonArea, profileLineString, radToDeg, staticMaps, xyzToTileID };
1592
+ export { ClientConfig, LanguageGeocoding, MapStyle, MapStyleVariant, ReferenceMapStyle, ServiceError, bufferToPixelDataBrowser, circumferenceAtLatitude, config, coordinates, data, elevation, expandMapStyle, geocoding, geolocation, getAutoLanguageGeocoding, getBufferToPixelDataParser, getTileCache, mapStylePresetList, math, misc, staticMaps, styleToStyle };
1507
1593
  //# sourceMappingURL=maptiler-client.mjs.map