@maptiler/client 2.4.0 → 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,18 @@
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
+
3
16
  ## 2.4.0
4
17
  ### New Features
5
18
  - Added `elevation` option to Geolocation API
@@ -2657,89 +2657,87 @@ function getBufferToPixelDataParser() {
2657
2657
  "An image file buffer to pixel data parser is necessary. Specify it in `config.bufferToPixelData`"
2658
2658
  );
2659
2659
  }
2660
+ function canParsePixelData() {
2661
+ return !!config.bufferToPixelData || typeof window !== "undefined";
2662
+ }
2660
2663
 
2661
- 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;
2662
2667
  let terrainTileJson = null;
2663
2668
  const customMessages = {
2664
2669
  403: "Key is missing, invalid or restricted"
2665
2670
  };
2666
- async function fetchTerrainTileJson(apiKey) {
2667
- const endpoint = new URL(terrainTileJsonURL, defaults.maptilerApiURL);
2668
- endpoint.searchParams.set("key", apiKey);
2669
- const urlWithParams = endpoint.toString();
2670
- const res = await callFetch(urlWithParams);
2671
- if (res.ok) {
2672
- terrainTileJson = await res.json();
2673
- return terrainTileJson;
2674
- } else {
2675
- if (!res.ok) {
2676
- throw new ServiceError(res, customMessages[res.status] ?? "");
2677
- }
2678
- }
2679
- }
2680
- async function at(position, options = {}) {
2681
- const apiKey = options.apiKey ?? config.apiKey;
2682
- if (!terrainTileJson) {
2683
- 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
+ );
2684
2676
  }
2685
- const maxZoom = terrainTileJson.maxzoom;
2686
- let zoom = ~~(options.zoom ?? maxZoom);
2687
- if (zoom > maxZoom || zoom < 0) {
2688
- zoom = maxZoom;
2689
- }
2690
- const tileIndex = math.wgs84ToTileIndex(position, zoom, false);
2691
- const tileX = ~~tileIndex[0];
2692
- const tileY = ~~tileIndex[1];
2693
- if (!terrainTileJson.tiles.length) {
2694
- throw new Error("Terrain tileJSON tile list is empty.");
2695
- }
2696
- const tileID = `terrain_${zoom.toString()}_${tileX.toString()}_${tileY.toString()}`;
2697
- let tilePixelData;
2698
- const cache = getTileCache();
2699
- if (cache.has(tileID)) {
2700
- tilePixelData = cache.get(tileID);
2701
- } else {
2702
- const tileURL = terrainTileJson.tiles[0].replace("{x}", tileX.toString()).replace("{y}", tileY.toString()).replace("{z}", zoom.toString());
2703
- const tileRes = await callFetch(tileURL);
2704
- if (!tileRes.ok) {
2705
- 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());
2706
2689
  }
2707
- const tileBuff = await tileRes.arrayBuffer();
2708
- const tileParser = getBufferToPixelDataParser();
2709
- tilePixelData = await tileParser(tileBuff);
2710
- cache.set(tileID, tilePixelData);
2711
- }
2712
- const pixelX = ~~(tilePixelData.width * (tileIndex[0] % 1));
2713
- const pixelY = ~~(tilePixelData.height * (tileIndex[1] % 1));
2714
- const pixelDataIndex = (pixelY * tilePixelData.width + pixelX) * tilePixelData.components;
2715
- const R = tilePixelData.pixels[pixelDataIndex];
2716
- const G = tilePixelData.pixels[pixelDataIndex + 1];
2717
- const B = tilePixelData.pixels[pixelDataIndex + 2];
2718
- const elevation2 = -1e4 + (R * 256 * 256 + G * 256 + B) * 0.1;
2719
- 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();
2720
2708
  }
2721
- async function batch(positions, options = {}) {
2722
- const apiKey = options.apiKey ?? config.apiKey;
2709
+ async function computeOnClient(positions, apiKey, zoom) {
2723
2710
  if (!terrainTileJson) {
2724
- 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
+ }
2725
2723
  }
2726
2724
  const tileParser = getBufferToPixelDataParser();
2727
2725
  const tileURLSchema = terrainTileJson.tiles[0];
2728
2726
  const cache = getTileCache();
2729
2727
  const maxZoom = terrainTileJson.maxzoom;
2730
- let zoom = ~~(options.zoom ?? maxZoom);
2731
- if (zoom > maxZoom || zoom < 0) {
2732
- zoom = maxZoom;
2728
+ let usedZoom = ~~(zoom ?? maxZoom);
2729
+ if (usedZoom > maxZoom || usedZoom < 0) {
2730
+ usedZoom = maxZoom;
2733
2731
  }
2734
2732
  const tileIndicesFloats = positions.map(
2735
- (position) => math.wgs84ToTileIndex(position, zoom, false)
2733
+ (position) => math.wgs84ToTileIndex(position, usedZoom, false)
2736
2734
  );
2737
2735
  const tileIndicesInteger = tileIndicesFloats.map((index) => [
2738
2736
  ~~index[0],
2739
2737
  ~~index[1]
2740
2738
  ]);
2741
2739
  const tileIDs = tileIndicesInteger.map(
2742
- (index) => `terrain_${zoom.toString()}_${index[0].toString()}_${index[1].toString()}`
2740
+ (index) => `terrain_${usedZoom.toString()}_${index[0].toString()}_${index[1].toString()}`
2743
2741
  );
2744
2742
  const uniqueTilesToFetch = Array.from(
2745
2743
  new Set(tileIDs.filter((tileID) => !cache.has(tileID)))
@@ -2795,6 +2793,17 @@ async function batch(positions, options = {}) {
2795
2793
  const elevation2 = -1e4 + (R * 256 * 256 + G * 256 + B) * 0.1;
2796
2794
  return [position[0], position[1], ~~(elevation2 * 1e3) / 1e3];
2797
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);
2798
2807
  if (options.smoothingKernelSize) {
2799
2808
  const kernelSize = ~~(options.smoothingKernelSize / 2) * 2 + 1;
2800
2809
  const elevations = elevatedPositions.map((pos) => pos[2]);
@@ -2815,6 +2824,7 @@ async function fromLineString(ls, options = {}) {
2815
2824
  if (ls.type !== "LineString") {
2816
2825
  throw new Error("The provided object is not a GeoJSON LineString");
2817
2826
  }
2827
+ options.computeOn ?? (options.computeOn = canParsePixelData() ? "client" : "server");
2818
2828
  const clone = structuredClone(ls);
2819
2829
  const elevatedPositions = await batch(clone.coordinates, options);
2820
2830
  clone.coordinates = elevatedPositions;
@@ -2824,6 +2834,7 @@ async function fromMultiLineString(ls, options = {}) {
2824
2834
  if (ls.type !== "MultiLineString") {
2825
2835
  throw new Error("The provided object is not a GeoJSON MultiLineString");
2826
2836
  }
2837
+ options.computeOn ?? (options.computeOn = canParsePixelData() ? "client" : "server");
2827
2838
  const clone = structuredClone(ls);
2828
2839
  const multiLengths = clone.coordinates.map((poss) => poss.length);
2829
2840
  const flattenPositions = clone.coordinates.flat();
@@ -2854,6 +2865,7 @@ exports.ReferenceMapStyle = ReferenceMapStyle;
2854
2865
  exports.ServiceError = ServiceError;
2855
2866
  exports.areSameLanguages = areSameLanguages;
2856
2867
  exports.bufferToPixelDataBrowser = bufferToPixelDataBrowser;
2868
+ exports.canParsePixelData = canParsePixelData;
2857
2869
  exports.circumferenceAtLatitude = circumferenceAtLatitude;
2858
2870
  exports.config = config;
2859
2871
  exports.coordinates = coordinates;