@maptiler/client 2.3.2 → 2.5.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # MapTiler Client Changelog
2
2
 
3
+ ## 2.5.0
4
+ ### New Features
5
+ - `at` and `batch` functions compute elevation on the server using MapTiler Elevation API by default
6
+ - Elevation supports Node.js: computed on server when `bufferToPixelData` is not provided
7
+ - Added `computeOn` option to force client/server elevation processing
8
+ - Added `canParsePixelData` function to check if elevation can be computed on the client
9
+
10
+ ### Bug Fixes
11
+ - `bufferToPixelData` can be undefined
12
+
13
+ ### Others
14
+ None
15
+
16
+ ## 2.4.0
17
+ ### New Features
18
+ - Added `elevation` option to Geolocation API
19
+
20
+ ### Bug Fixes
21
+ None
22
+
23
+ ### Others
24
+ None
25
+
3
26
  ## 2.3.2
4
27
  ### New Features
5
28
  None
@@ -1156,6 +1156,12 @@ const customMessages$3 = {
1156
1156
  async function info(options = {}) {
1157
1157
  const endpoint = new URL(`geolocation/ip.json`, defaults.maptilerApiURL);
1158
1158
  endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
1159
+ if ("elevation" in options) {
1160
+ endpoint.searchParams.set(
1161
+ "elevation",
1162
+ options.elevation ? "true" : "false"
1163
+ );
1164
+ }
1159
1165
  const urlWithParams = endpoint.toString();
1160
1166
  const res = await callFetch(urlWithParams);
1161
1167
  if (!res.ok) {
@@ -2651,89 +2657,87 @@ function getBufferToPixelDataParser() {
2651
2657
  "An image file buffer to pixel data parser is necessary. Specify it in `config.bufferToPixelData`"
2652
2658
  );
2653
2659
  }
2660
+ function canParsePixelData() {
2661
+ return !!config.bufferToPixelData || typeof window !== "undefined";
2662
+ }
2654
2663
 
2655
- const terrainTileJsonURL = "tiles/terrain-rgb-v2/tiles.json";
2664
+ const TERRAIN_TILESET = "terrain-rgb-v2";
2665
+ const API_BATCH_SIZE = 50;
2666
+ const API_WARN_SIZE = 1e3;
2656
2667
  let terrainTileJson = null;
2657
2668
  const customMessages = {
2658
2669
  403: "Key is missing, invalid or restricted"
2659
2670
  };
2660
- async function fetchTerrainTileJson(apiKey) {
2661
- const endpoint = new URL(terrainTileJsonURL, defaults.maptilerApiURL);
2662
- endpoint.searchParams.set("key", apiKey);
2663
- const urlWithParams = endpoint.toString();
2664
- const res = await callFetch(urlWithParams);
2665
- if (res.ok) {
2666
- terrainTileJson = await res.json();
2667
- return terrainTileJson;
2668
- } else {
2669
- if (!res.ok) {
2670
- throw new ServiceError(res, customMessages[res.status] ?? "");
2671
- }
2672
- }
2673
- }
2674
- async function at(position, options = {}) {
2675
- const apiKey = options.apiKey ?? config.apiKey;
2676
- if (!terrainTileJson) {
2677
- await fetchTerrainTileJson(apiKey);
2671
+ async function computeOnServer(positions, apiKey) {
2672
+ if (positions.length > API_WARN_SIZE) {
2673
+ console.warn(
2674
+ "Computing elevation for complex geometries is discouraged - simplify the geometry before proceeding"
2675
+ );
2678
2676
  }
2679
- const maxZoom = terrainTileJson.maxzoom;
2680
- let zoom = ~~(options.zoom ?? maxZoom);
2681
- if (zoom > maxZoom || zoom < 0) {
2682
- zoom = maxZoom;
2683
- }
2684
- const tileIndex = math.wgs84ToTileIndex(position, zoom, false);
2685
- const tileX = ~~tileIndex[0];
2686
- const tileY = ~~tileIndex[1];
2687
- if (!terrainTileJson.tiles.length) {
2688
- throw new Error("Terrain tileJSON tile list is empty.");
2689
- }
2690
- const tileID = `terrain_${zoom.toString()}_${tileX.toString()}_${tileY.toString()}`;
2691
- let tilePixelData;
2692
- const cache = getTileCache();
2693
- if (cache.has(tileID)) {
2694
- tilePixelData = cache.get(tileID);
2695
- } else {
2696
- const tileURL = terrainTileJson.tiles[0].replace("{x}", tileX.toString()).replace("{y}", tileY.toString()).replace("{z}", zoom.toString());
2697
- const tileRes = await callFetch(tileURL);
2698
- if (!tileRes.ok) {
2699
- throw new ServiceError(tileRes, customMessages[tileRes.status] ?? "");
2677
+ const parts = Math.ceil(positions.length / API_BATCH_SIZE);
2678
+ const respPromises = Array.from({ length: parts }, () => null).map(
2679
+ (_, part) => {
2680
+ const startPos = part * API_BATCH_SIZE;
2681
+ const batch2 = positions.slice(startPos, startPos + API_BATCH_SIZE);
2682
+ const batchEncoded = batch2.map((pos) => pos.join(",")).join(";");
2683
+ const endpoint = new URL(
2684
+ `elevation/${batchEncoded}.json`,
2685
+ defaults.maptilerApiURL
2686
+ );
2687
+ endpoint.searchParams.set("key", apiKey);
2688
+ return callFetch(endpoint.toString());
2700
2689
  }
2701
- const tileBuff = await tileRes.arrayBuffer();
2702
- const tileParser = getBufferToPixelDataParser();
2703
- tilePixelData = await tileParser(tileBuff);
2704
- cache.set(tileID, tilePixelData);
2705
- }
2706
- const pixelX = ~~(tilePixelData.width * (tileIndex[0] % 1));
2707
- const pixelY = ~~(tilePixelData.height * (tileIndex[1] % 1));
2708
- const pixelDataIndex = (pixelY * tilePixelData.width + pixelX) * tilePixelData.components;
2709
- const R = tilePixelData.pixels[pixelDataIndex];
2710
- const G = tilePixelData.pixels[pixelDataIndex + 1];
2711
- const B = tilePixelData.pixels[pixelDataIndex + 2];
2712
- const elevation2 = -1e4 + (R * 256 * 256 + G * 256 + B) * 0.1;
2713
- return [position[0], position[1], elevation2];
2690
+ );
2691
+ const resps = await Promise.allSettled(respPromises);
2692
+ const jsons = await Promise.all(
2693
+ resps.map(async (resp) => {
2694
+ if (resp.status === "rejected") {
2695
+ throw new Error(
2696
+ `Some segments could not be fetched, error: ${resp.reason}`
2697
+ );
2698
+ }
2699
+ if (!resp.value.ok) {
2700
+ throw new Error(
2701
+ `Some segments could not be fetched, response: ${resp.value.status} ${await resp.value.text()}, url: ${resp.value.url}`
2702
+ );
2703
+ }
2704
+ return resp.value.json();
2705
+ })
2706
+ );
2707
+ return jsons.flat();
2714
2708
  }
2715
- async function batch(positions, options = {}) {
2716
- const apiKey = options.apiKey ?? config.apiKey;
2709
+ async function computeOnClient(positions, apiKey, zoom) {
2717
2710
  if (!terrainTileJson) {
2718
- await fetchTerrainTileJson(apiKey);
2711
+ const endpoint = new URL(
2712
+ `tiles/${TERRAIN_TILESET}/tiles.json`,
2713
+ defaults.maptilerApiURL
2714
+ );
2715
+ endpoint.searchParams.set("key", apiKey);
2716
+ const urlWithParams = endpoint.toString();
2717
+ const res = await callFetch(urlWithParams);
2718
+ if (res.ok) {
2719
+ terrainTileJson = await res.json();
2720
+ } else {
2721
+ throw new ServiceError(res, customMessages[res.status] ?? "");
2722
+ }
2719
2723
  }
2720
2724
  const tileParser = getBufferToPixelDataParser();
2721
2725
  const tileURLSchema = terrainTileJson.tiles[0];
2722
2726
  const cache = getTileCache();
2723
2727
  const maxZoom = terrainTileJson.maxzoom;
2724
- let zoom = ~~(options.zoom ?? maxZoom);
2725
- if (zoom > maxZoom || zoom < 0) {
2726
- zoom = maxZoom;
2728
+ let usedZoom = ~~(zoom ?? maxZoom);
2729
+ if (usedZoom > maxZoom || usedZoom < 0) {
2730
+ usedZoom = maxZoom;
2727
2731
  }
2728
2732
  const tileIndicesFloats = positions.map(
2729
- (position) => math.wgs84ToTileIndex(position, zoom, false)
2733
+ (position) => math.wgs84ToTileIndex(position, usedZoom, false)
2730
2734
  );
2731
2735
  const tileIndicesInteger = tileIndicesFloats.map((index) => [
2732
2736
  ~~index[0],
2733
2737
  ~~index[1]
2734
2738
  ]);
2735
2739
  const tileIDs = tileIndicesInteger.map(
2736
- (index) => `terrain_${zoom.toString()}_${index[0].toString()}_${index[1].toString()}`
2740
+ (index) => `terrain_${usedZoom.toString()}_${index[0].toString()}_${index[1].toString()}`
2737
2741
  );
2738
2742
  const uniqueTilesToFetch = Array.from(
2739
2743
  new Set(tileIDs.filter((tileID) => !cache.has(tileID)))
@@ -2789,6 +2793,17 @@ async function batch(positions, options = {}) {
2789
2793
  const elevation2 = -1e4 + (R * 256 * 256 + G * 256 + B) * 0.1;
2790
2794
  return [position[0], position[1], ~~(elevation2 * 1e3) / 1e3];
2791
2795
  });
2796
+ return elevatedPositions;
2797
+ }
2798
+ async function at(position, options = {}) {
2799
+ const elevatedPositions = await batch([position], options);
2800
+ return elevatedPositions[0];
2801
+ }
2802
+ async function batch(positions, options = {}) {
2803
+ if (positions.length === 0)
2804
+ return [];
2805
+ const apiKey = options.apiKey ?? config.apiKey;
2806
+ const elevatedPositions = options.computeOn === "client" ? await computeOnClient(positions, apiKey, options.zoom) : await computeOnServer(positions, apiKey);
2792
2807
  if (options.smoothingKernelSize) {
2793
2808
  const kernelSize = ~~(options.smoothingKernelSize / 2) * 2 + 1;
2794
2809
  const elevations = elevatedPositions.map((pos) => pos[2]);
@@ -2809,6 +2824,7 @@ async function fromLineString(ls, options = {}) {
2809
2824
  if (ls.type !== "LineString") {
2810
2825
  throw new Error("The provided object is not a GeoJSON LineString");
2811
2826
  }
2827
+ options.computeOn ?? (options.computeOn = canParsePixelData() ? "client" : "server");
2812
2828
  const clone = structuredClone(ls);
2813
2829
  const elevatedPositions = await batch(clone.coordinates, options);
2814
2830
  clone.coordinates = elevatedPositions;
@@ -2818,6 +2834,7 @@ async function fromMultiLineString(ls, options = {}) {
2818
2834
  if (ls.type !== "MultiLineString") {
2819
2835
  throw new Error("The provided object is not a GeoJSON MultiLineString");
2820
2836
  }
2837
+ options.computeOn ?? (options.computeOn = canParsePixelData() ? "client" : "server");
2821
2838
  const clone = structuredClone(ls);
2822
2839
  const multiLengths = clone.coordinates.map((poss) => poss.length);
2823
2840
  const flattenPositions = clone.coordinates.flat();
@@ -2848,6 +2865,7 @@ exports.ReferenceMapStyle = ReferenceMapStyle;
2848
2865
  exports.ServiceError = ServiceError;
2849
2866
  exports.areSameLanguages = areSameLanguages;
2850
2867
  exports.bufferToPixelDataBrowser = bufferToPixelDataBrowser;
2868
+ exports.canParsePixelData = canParsePixelData;
2851
2869
  exports.circumferenceAtLatitude = circumferenceAtLatitude;
2852
2870
  exports.config = config;
2853
2871
  exports.coordinates = coordinates;