@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,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var webMercProjection = require('web-merc-projection');
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
@@ -147,17 +151,18 @@ class ServiceError extends Error {
147
151
  }
148
152
  }
149
153
 
150
- const customMessages$3 = {
154
+ const customMessages$4 = {
151
155
  400: "Query too long / Invalid parameters",
152
156
  403: "Key is missing, invalid or restricted"
153
157
  };
154
158
  function addLanguageGeocodingOptions(searchParams, options) {
155
- if (options.language == void 0) {
159
+ const { language } = options;
160
+ if (language == void 0) {
156
161
  return;
157
162
  }
158
163
  const languages = Array.from(
159
164
  new Set(
160
- (Array.isArray(options.language) ? options.language : [options.language]).map(
165
+ (Array.isArray(language) ? language : [language]).map(
161
166
  (lang) => lang === LanguageGeocoding.AUTO ? getAutoLanguageGeocoding() : lang
162
167
  )
163
168
  )
@@ -165,31 +170,39 @@ function addLanguageGeocodingOptions(searchParams, options) {
165
170
  searchParams.set("language", languages);
166
171
  }
167
172
  function addCommonForwardAndReverseGeocodingOptions(searchParams, options) {
168
- searchParams.set("key", options.apiKey ?? config.apiKey);
169
- if (options.limit != void 0) {
170
- 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));
171
177
  }
172
- if (options.types != void 0) {
173
- searchParams.set("types", options.types.join(","));
178
+ if (types != void 0) {
179
+ searchParams.set("types", types.join(","));
180
+ }
181
+ if (excludeTypes != void 0) {
182
+ searchParams.set("excludeTypes", String(excludeTypes));
174
183
  }
175
184
  addLanguageGeocodingOptions(searchParams, options);
176
185
  }
177
186
  function addForwardGeocodingOptions(searchParams, options) {
178
187
  addCommonForwardAndReverseGeocodingOptions(searchParams, options);
179
- if (options.bbox != void 0) {
180
- searchParams.set("bbox", options.bbox.join(","));
181
- }
182
- if (options.proximity != void 0) {
183
- 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
+ );
184
197
  }
185
- if (options.country != void 0) {
186
- searchParams.set("country", options.country.join(","));
198
+ if (country != void 0) {
199
+ searchParams.set("country", country.join(","));
187
200
  }
188
- if (options.fuzzyMatch != void 0) {
189
- searchParams.set("fuzzyMatch", options.fuzzyMatch ? "true" : "false");
201
+ if (fuzzyMatch != void 0) {
202
+ searchParams.set("fuzzyMatch", fuzzyMatch ? "true" : "false");
190
203
  }
191
- if (options.autocomplete != void 0) {
192
- searchParams.set("autocomplete", options.autocomplete ? "true" : "false");
204
+ if (autocomplete != void 0) {
205
+ searchParams.set("autocomplete", autocomplete ? "true" : "false");
193
206
  }
194
207
  }
195
208
  async function forward(query, options = {}) {
@@ -205,7 +218,7 @@ async function forward(query, options = {}) {
205
218
  const urlWithParams = endpoint.toString();
206
219
  const res = await callFetch(urlWithParams);
207
220
  if (!res.ok) {
208
- throw new ServiceError(res, customMessages$3[res.status] ?? "");
221
+ throw new ServiceError(res, customMessages$4[res.status] ?? "");
209
222
  }
210
223
  const obj = await res.json();
211
224
  return obj;
@@ -222,7 +235,7 @@ async function reverse(position, options = {}) {
222
235
  const urlWithParams = endpoint.toString();
223
236
  const res = await callFetch(urlWithParams);
224
237
  if (!res.ok) {
225
- throw new ServiceError(res, customMessages$3[res.status] ?? "");
238
+ throw new ServiceError(res, customMessages$4[res.status] ?? "");
226
239
  }
227
240
  const obj = await res.json();
228
241
  return obj;
@@ -234,12 +247,12 @@ async function byId(id, options = {}) {
234
247
  const urlWithParams = endpoint.toString();
235
248
  const res = await callFetch(urlWithParams);
236
249
  if (!res.ok) {
237
- throw new ServiceError(res, customMessages$3[res.status] ?? "");
250
+ throw new ServiceError(res, customMessages$4[res.status] ?? "");
238
251
  }
239
252
  const obj = await res.json();
240
253
  return obj;
241
254
  }
242
- async function batch(queries, options = {}) {
255
+ async function batch$1(queries, options = {}) {
243
256
  if (!queries.length) {
244
257
  return [];
245
258
  }
@@ -253,7 +266,7 @@ async function batch(queries, options = {}) {
253
266
  const urlWithParams = endpoint.toString();
254
267
  const res = await callFetch(urlWithParams);
255
268
  if (!res.ok) {
256
- throw new ServiceError(res, customMessages$3[res.status] ?? "");
269
+ throw new ServiceError(res, customMessages$4[res.status] ?? "");
257
270
  }
258
271
  const obj = await res.json();
259
272
  return queries.length === 1 ? [obj] : obj;
@@ -262,11 +275,11 @@ const geocoding = {
262
275
  forward,
263
276
  reverse,
264
277
  byId,
265
- batch,
278
+ batch: batch$1,
266
279
  language: LanguageGeocoding
267
280
  };
268
281
 
269
- const customMessages$2 = {
282
+ const customMessages$3 = {
270
283
  403: "Key is missing, invalid or restricted"
271
284
  };
272
285
  async function info(options = {}) {
@@ -277,7 +290,7 @@ async function info(options = {}) {
277
290
  if (!res.ok) {
278
291
  throw new ServiceError(
279
292
  res,
280
- res.status in customMessages$2 ? customMessages$2[res.status] : ""
293
+ res.status in customMessages$3 ? customMessages$3[res.status] : ""
281
294
  );
282
295
  }
283
296
  const obj = await res.json();
@@ -287,7 +300,7 @@ const geolocation = {
287
300
  info
288
301
  };
289
302
 
290
- const customMessages$1 = {
303
+ const customMessages$2 = {
291
304
  403: "Key is missing, invalid or restricted"
292
305
  };
293
306
  async function search(query, options = {}) {
@@ -316,7 +329,7 @@ async function search(query, options = {}) {
316
329
  if (!res.ok) {
317
330
  throw new ServiceError(
318
331
  res,
319
- res.status in customMessages$1 ? customMessages$1[res.status] : ""
332
+ res.status in customMessages$2 ? customMessages$2[res.status] : ""
320
333
  );
321
334
  }
322
335
  const obj = await res.json();
@@ -346,7 +359,7 @@ async function transform(positions, options = {}) {
346
359
  if (!res.ok) {
347
360
  throw new ServiceError(
348
361
  res,
349
- res.status in customMessages$1 ? customMessages$1[res.status] : ""
362
+ res.status in customMessages$2 ? customMessages$2[res.status] : ""
350
363
  );
351
364
  }
352
365
  const obj = await res.json();
@@ -357,7 +370,7 @@ const coordinates = {
357
370
  transform
358
371
  };
359
372
 
360
- const customMessages = {
373
+ const customMessages$1 = {
361
374
  403: "Key is missing, invalid or restricted"
362
375
  };
363
376
  async function get(dataId, options = {}) {
@@ -374,7 +387,7 @@ async function get(dataId, options = {}) {
374
387
  if (!res.ok) {
375
388
  throw new ServiceError(
376
389
  res,
377
- res.status in customMessages ? customMessages[res.status] : ""
390
+ res.status in customMessages$1 ? customMessages$1[res.status] : ""
378
391
  );
379
392
  }
380
393
  const obj = await res.json();
@@ -981,6 +994,36 @@ function styleToStyle(style) {
981
994
  }
982
995
  const MapStyle = buildMapStyles();
983
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
+ }
984
1027
  function getSqSegDist(p, p1, p2) {
985
1028
  let x = p1[0], y = p1[1], dx = p2[0] - x, dy = p2[1] - y;
986
1029
  if (dx !== 0 || dy !== 0) {
@@ -1031,6 +1074,10 @@ function simplify(points, tolerance) {
1031
1074
  const simplePoints = simplifyDouglasPeucker(points, sqTolerance);
1032
1075
  return simplePoints;
1033
1076
  }
1077
+ const misc = {
1078
+ extractLineStrings,
1079
+ simplify
1080
+ };
1034
1081
 
1035
1082
  function staticMapMarkerToString(marker, includeColor = true) {
1036
1083
  let str = `${marker[0]},${marker[1]}`;
@@ -1044,7 +1091,7 @@ function simplifyAndStringify(path, maxNbChar = 3e3) {
1044
1091
  let tolerance = 5e-6;
1045
1092
  const toleranceStep = 1e-5;
1046
1093
  while (str.length > maxNbChar) {
1047
- const simplerPath = simplify(path, tolerance);
1094
+ const simplerPath = misc.simplify(path, tolerance);
1048
1095
  str = simplerPath.map((point) => `${point[0]},${point[1]}`).join("|");
1049
1096
  tolerance += toleranceStep;
1050
1097
  }
@@ -1216,294 +1263,333 @@ const staticMaps = {
1216
1263
  automatic
1217
1264
  };
1218
1265
 
1219
- const earthRadius = 63710088e-1;
1220
- function mToFt(m) {
1221
- return m * 3.28084;
1266
+ const EARTH_RADIUS = 63710088e-1;
1267
+ const EARTH_CIRCUMFERENCE = 2 * Math.PI * EARTH_RADIUS;
1268
+ function longitudeToMercatorX(lng) {
1269
+ return (180 + lng) / 360;
1222
1270
  }
1223
- function degToRad(degrees) {
1224
- return degrees % 360 * Math.PI / 180;
1271
+ function latitudeToMercatorY(lat) {
1272
+ return (180 - 180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360))) / 360;
1225
1273
  }
1226
- function radToDeg(radians) {
1227
- return radians * 180 / Math.PI;
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])];
1228
1290
  }
1229
- function getZoomLevelResolution(latitude, zoom, tileSize = 512) {
1230
- return Math.cos(latitude * Math.PI / 180) * 2 * Math.PI * 6378137 / (tileSize * 2 ** zoom) * 3;
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;
1231
1298
  }
1232
- function xyzToTileID(x, y, zoom) {
1233
- return ((1 << zoom) * y + x) * 32 + zoom;
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;
1234
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
+ };
1235
1372
 
1236
- function area(area2) {
1237
- const geometry = "geometry" in area2 ? area2.geometry : area2;
1238
- const type = geometry.type;
1239
- if (type === "MultiPolygon") {
1240
- return multiPolygonArea(geometry.coordinates);
1373
+ let tileCache = null;
1374
+ function getTileCache() {
1375
+ if (!tileCache) {
1376
+ tileCache = new QuickLRU({ maxSize: config.tileCacheSize });
1241
1377
  }
1242
- return polygonArea(geometry.coordinates);
1378
+ return tileCache;
1243
1379
  }
1244
- function multiPolygonArea(multiPoly) {
1245
- const coords = "coordinates" in multiPoly ? multiPoly.coordinates : multiPoly;
1246
- let total = 0;
1247
- for (const polygon of coords) {
1248
- total += polygonArea(polygon);
1249
- }
1250
- return total;
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
+ };
1251
1395
  }
1252
- function polygonArea(poly) {
1253
- const coords = "coordinates" in poly ? poly.coordinates : poly;
1254
- let total = 0;
1255
- for (const ring of coords) {
1256
- total += ringArea(ring);
1396
+ function getBufferToPixelDataParser() {
1397
+ if (config.bufferToPixelData) {
1398
+ return config.bufferToPixelData;
1257
1399
  }
1258
- return total;
1259
- }
1260
- function ringArea(coords) {
1261
- let p1;
1262
- let p2;
1263
- let p3;
1264
- let lowerIndex;
1265
- let middleIndex;
1266
- let upperIndex;
1267
- let i;
1268
- let total = 0;
1269
- const coordsLength = coords.length;
1270
- if (coordsLength > 2) {
1271
- for (i = 0; i < coordsLength; i++) {
1272
- if (i === coordsLength - 2) {
1273
- lowerIndex = coordsLength - 2;
1274
- middleIndex = coordsLength - 1;
1275
- upperIndex = 0;
1276
- } else if (i === coordsLength - 1) {
1277
- lowerIndex = coordsLength - 1;
1278
- middleIndex = 0;
1279
- upperIndex = 1;
1280
- } else {
1281
- lowerIndex = i;
1282
- middleIndex = i + 1;
1283
- upperIndex = i + 2;
1284
- }
1285
- p1 = coords[lowerIndex];
1286
- p2 = coords[middleIndex];
1287
- p3 = coords[upperIndex];
1288
- total += (degToRad(p3[0]) - degToRad(p1[0])) * Math.sin(degToRad(p2[1]));
1289
- }
1290
- total = total * earthRadius * earthRadius / 2;
1400
+ if (typeof window !== "undefined") {
1401
+ return bufferToPixelDataBrowser;
1291
1402
  }
1292
- return Math.abs(total);
1403
+ throw new Error(
1404
+ "An image file buffer to pixel data parser is necessary. Specify it in `config.bufferToPixelData`"
1405
+ );
1293
1406
  }
1294
1407
 
1295
- function lineDistance(line) {
1296
- const coordinates = "geometry" in line ? line.geometry.coordinates : "coordinates" in line ? line.coordinates : line;
1297
- let distance = 0;
1298
- let prevCoord;
1299
- for (const coordinate of coordinates) {
1300
- if (prevCoord !== void 0) {
1301
- distance += pointDistance(prevCoord, coordinate);
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] ?? "");
1302
1424
  }
1303
- prevCoord = coordinate;
1304
1425
  }
1305
- return distance;
1306
1426
  }
1307
- function pointDistance(from, to) {
1308
- const { pow, sin, cos, sqrt, atan2 } = Math;
1309
- const dLat = degToRad(to[1] - from[1]);
1310
- const dLon = degToRad(to[0] - from[0]);
1311
- const lat1 = degToRad(from[1]);
1312
- const lat2 = degToRad(to[1]);
1313
- const a = pow(sin(dLat / 2), 2) + pow(sin(dLon / 2), 2) * cos(lat1) * cos(lat2);
1314
- return 2 * atan2(sqrt(a), sqrt(1 - a)) * earthRadius;
1315
- }
1316
-
1317
- function tileCover(coordinates, zoom, tileSize) {
1318
- const tileHash = /* @__PURE__ */ new Map();
1319
- const tiles = [];
1320
- const coords = [];
1321
- const resolution = getZoomLevelResolution(coordinates[0][1], zoom, tileSize);
1322
- const samples = sampleProfileLine(coordinates, resolution);
1323
- for (const sample of samples) {
1324
- const coordinate = sample;
1325
- const [tileX, tileY] = webMercProjection.llToTile(coordinate, zoom, tileSize);
1326
- const id = xyzToTileID(tileX, tileY, zoom);
1327
- const tile = { id, x: tileX, y: tileY, z: zoom };
1328
- tileHash.set(id, tile);
1329
- coords.push({ coordinate, tile });
1330
- }
1331
- for (const tile of tileHash.values())
1332
- tiles.push(tile);
1333
- return { coords, tiles };
1334
- }
1335
- function sampleProfileLine(coordinates, resolution) {
1336
- const samples = [];
1337
- let prevCoord;
1338
- for (const coord of coordinates) {
1339
- if (prevCoord !== void 0) {
1340
- const dist = pointDistance(
1341
- prevCoord,
1342
- coord
1343
- );
1344
- const numSamples = Math.ceil(dist / resolution);
1345
- for (let i = 0; i <= numSamples - 1; i++) {
1346
- const sample = [
1347
- prevCoord[0] + (coord[0] - prevCoord[0]) * (i / numSamples),
1348
- prevCoord[1] + (coord[1] - prevCoord[1]) * (i / numSamples)
1349
- ];
1350
- samples.push(sample);
1351
- }
1352
- } else {
1353
- samples.push(coord);
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] ?? "");
1354
1453
  }
1355
- prevCoord = coord;
1356
- }
1357
- return samples;
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];
1358
1467
  }
1359
-
1360
- function getElevation(coord, tile, tileSize, tileImage, elevationParser = defaultElevationParser) {
1361
- const { channels, image } = tileImage;
1362
- let [x, y] = webMercProjection.llToTilePx(coord, tile, tileSize);
1363
- x = clampPixel(x, tileSize);
1364
- y = clampPixel(y, tileSize);
1365
- const index = (y * tileSize + x) * channels;
1366
- return elevationParser(
1367
- image[index],
1368
- image[index + 1],
1369
- image[index + 2],
1370
- channels === 4 ? image[index + 3] : 0
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)
1371
1483
  );
1372
- }
1373
- function clampPixel(n, tileSize) {
1374
- return Math.max(0, Math.min(tileSize, Math.floor(n * tileSize)));
1375
- }
1376
- function defaultElevationParser(r, g, b) {
1377
- return -1e4 + (r * 256 * 256 + g * 256 + b) * 0.1;
1378
- }
1379
-
1380
- async function profileLineString(path, options) {
1381
- const coordinates = "geometry" in path ? path.geometry.coordinates : path.coordinates;
1382
- const { coords, tiles } = tileCover(
1383
- coordinates,
1384
- options.zoom ?? 13,
1385
- options.tileSize ?? 512
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()}`
1386
1490
  );
1387
- const tileCache = await getTiles(tiles, options.tileRequest);
1388
- let points = getElevations(
1389
- coords,
1390
- tileCache,
1391
- options.tileSize ?? 512,
1392
- options.elevationParser
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())
1393
1496
  );
1394
- if (options.smooth === true)
1395
- points = smoothElevation(points);
1396
- let output = buildOutput(points);
1397
- if (options.metric === "ft")
1398
- output = toFeet(output);
1399
- return output;
1400
- }
1401
- async function getTiles(tiles, tileRequest) {
1402
- const tileCache = /* @__PURE__ */ new Map();
1403
- const requests = [];
1404
- for (const tile of tiles) {
1405
- requests.push(
1406
- tileRequest(tile.x, tile.y, tile.z).then((res) => {
1407
- tileCache.set(tile.id, res);
1408
- return res;
1409
- }).catch((err) => {
1410
- console.error(err);
1411
- return void 0;
1412
- })
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] ?? ""
1413
1510
  );
1414
1511
  }
1415
- await Promise.allSettled(requests);
1416
- return tileCache;
1417
- }
1418
- function getElevations(coords, tileCache, tileSize, elevationParser) {
1419
- const points = [];
1420
- let curDistance = 0;
1421
- let prevCoord;
1422
- for (const { tile, coordinate } of coords) {
1423
- const cTile = tileCache.get(tile.id);
1424
- if (cTile === void 0)
1425
- throw new Error(
1426
- `Missing tile ${tile.id} (${tile.x}-${tile.y}-${tile.z})`
1427
- );
1428
- const elevation = getElevation(
1429
- coordinate,
1430
- [tile.z, tile.x, tile.y],
1431
- tileSize,
1432
- cTile,
1433
- elevationParser
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
1434
1537
  );
1435
- points.push({
1436
- distance: curDistance,
1437
- elevation,
1438
- coordinate,
1439
- tile
1440
- });
1441
- if (prevCoord !== void 0) {
1442
- curDistance += pointDistance(prevCoord, coordinate);
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;
1443
1557
  }
1444
- prevCoord = coordinate;
1445
1558
  }
1446
- return points;
1559
+ return elevatedPositions;
1447
1560
  }
1448
- function buildOutput(points) {
1449
- let minElevation = Infinity;
1450
- let maxElevation = -Infinity;
1451
- let totalElevation = 0;
1452
- for (const point of points) {
1453
- if (point.elevation < minElevation)
1454
- minElevation = point.elevation;
1455
- if (point.elevation > maxElevation)
1456
- maxElevation = point.elevation;
1457
- totalElevation += point.elevation;
1458
- }
1459
- return {
1460
- distance: points[points.length - 1].distance,
1461
- minElevation,
1462
- maxElevation,
1463
- avgElevation: totalElevation / points.length,
1464
- startElevation: points[0].elevation,
1465
- endElevation: points[points.length - 1].elevation,
1466
- points
1467
- };
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;
1468
1569
  }
1469
- function smoothElevation(points) {
1470
- const newPoints = [];
1471
- let prevPoint;
1472
- for (let i = 0; i < points.length; i++) {
1473
- const point = points[i];
1474
- const nextPoint = points[i + 1] ?? points[i];
1475
- if (prevPoint === void 0) {
1476
- newPoints.push(point);
1477
- } else {
1478
- const newPoint = {
1479
- distance: point.distance,
1480
- elevation: (prevPoint.elevation + point.elevation + nextPoint.elevation) / 3,
1481
- coordinate: point.coordinate,
1482
- tile: point.tile
1483
- };
1484
- newPoints.push(newPoint);
1485
- }
1486
- prevPoint = point;
1487
- }
1488
- return newPoints;
1489
- }
1490
- function toFeet(input) {
1491
- const output = {
1492
- distance: mToFt(input.distance),
1493
- minElevation: mToFt(input.minElevation),
1494
- maxElevation: mToFt(input.maxElevation),
1495
- avgElevation: mToFt(input.avgElevation),
1496
- startElevation: mToFt(input.startElevation),
1497
- endElevation: mToFt(input.endElevation),
1498
- points: input.points.map(({ distance, elevation, coordinate, tile }) => ({
1499
- distance: mToFt(distance),
1500
- elevation: mToFt(elevation),
1501
- coordinate,
1502
- tile
1503
- }))
1504
- };
1505
- return output;
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;
1506
1586
  }
1587
+ const elevation = {
1588
+ at,
1589
+ batch,
1590
+ fromLineString,
1591
+ fromMultiLineString
1592
+ };
1507
1593
 
1508
1594
  exports.ClientConfig = ClientConfig;
1509
1595
  exports.LanguageGeocoding = LanguageGeocoding;
@@ -1511,25 +1597,21 @@ exports.MapStyle = MapStyle;
1511
1597
  exports.MapStyleVariant = MapStyleVariant;
1512
1598
  exports.ReferenceMapStyle = ReferenceMapStyle;
1513
1599
  exports.ServiceError = ServiceError;
1514
- exports.area = area;
1600
+ exports.bufferToPixelDataBrowser = bufferToPixelDataBrowser;
1601
+ exports.circumferenceAtLatitude = circumferenceAtLatitude;
1515
1602
  exports.config = config;
1516
1603
  exports.coordinates = coordinates;
1517
1604
  exports.data = data;
1518
- exports.defaultElevationParser = defaultElevationParser;
1519
- exports.degToRad = degToRad;
1520
- exports.earthRadius = earthRadius;
1605
+ exports.elevation = elevation;
1521
1606
  exports.expandMapStyle = expandMapStyle;
1522
1607
  exports.geocoding = geocoding;
1523
1608
  exports.geolocation = geolocation;
1524
- exports.getZoomLevelResolution = getZoomLevelResolution;
1525
- exports.lineDistance = lineDistance;
1526
- exports.mToFt = mToFt;
1609
+ exports.getAutoLanguageGeocoding = getAutoLanguageGeocoding;
1610
+ exports.getBufferToPixelDataParser = getBufferToPixelDataParser;
1611
+ exports.getTileCache = getTileCache;
1527
1612
  exports.mapStylePresetList = mapStylePresetList;
1528
- exports.multiPolygonArea = multiPolygonArea;
1529
- exports.pointDistance = pointDistance;
1530
- exports.polygonArea = polygonArea;
1531
- exports.profileLineString = profileLineString;
1532
- exports.radToDeg = radToDeg;
1613
+ exports.math = math;
1614
+ exports.misc = misc;
1533
1615
  exports.staticMaps = staticMaps;
1534
- exports.xyzToTileID = xyzToTileID;
1616
+ exports.styleToStyle = styleToStyle;
1535
1617
  //# sourceMappingURL=maptiler-client.cjs.map