@maptiler/sdk 4.0.2-rc.1 → 4.0.3-projection.alpha.1

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/README.md CHANGED
@@ -1843,6 +1843,131 @@ import { config } from "@maptiler/sdk";
1843
1843
  config.caching = false;
1844
1844
  ```
1845
1845
 
1846
+ ### Prefetching (experimental)
1847
+
1848
+ The SDK can prefetch tiles ahead of camera movements and store them in the browser cache, so they render instantly when the map arrives at the destination. This is an **experimental** feature — the API may change in future releases.
1849
+
1850
+ > ⚠️ **API Key Usage**: Every prefetched tile counts against your MapTiler Cloud API key quota. Use narrow zoom ranges and small geographic areas where possible.
1851
+
1852
+ #### Enabling
1853
+
1854
+ Pass `useExperimentalTilePreloading: true` when creating the map:
1855
+
1856
+ ```ts
1857
+ import { Map } from "@maptiler/sdk";
1858
+
1859
+ const map = new Map({
1860
+ container: "map",
1861
+ useExperimentalTilePreloading: true,
1862
+ });
1863
+ ```
1864
+
1865
+ #### Prefetching on camera animations
1866
+
1867
+ Once enabled, pass `experimental_preload` in the options of any camera animation method. Tiles are fetched before the animation starts, so they are ready when the camera arrives.
1868
+
1869
+ **`flyTo`** — prefetches tiles visible at the destination:
1870
+
1871
+ ```ts
1872
+ map.flyTo({
1873
+ center: [-74.006, 40.7128],
1874
+ zoom: 14,
1875
+ experimental_preload: { maxTiles: 256 },
1876
+ });
1877
+ ```
1878
+
1879
+ **`panTo`** — prefetches tiles along the pan path:
1880
+
1881
+ ```ts
1882
+ map.panTo([-74.006, 40.7128], {
1883
+ experimental_preload: {},
1884
+ });
1885
+ ```
1886
+
1887
+ **`easeTo`** — prefetches tiles along the ease path:
1888
+
1889
+ ```ts
1890
+ map.easeTo({
1891
+ center: [-74.006, 40.7128],
1892
+ zoom: 12,
1893
+ experimental_preload: {},
1894
+ });
1895
+ ```
1896
+
1897
+ **`fitBounds`** — prefetches tiles for the destination viewport:
1898
+
1899
+ ```ts
1900
+ map.fitBounds([[-74.1, 40.6], [-73.9, 40.8]], {
1901
+ experimental_preload: { maxTiles: 128 },
1902
+ });
1903
+ ```
1904
+
1905
+ **`zoomTo`** — prefetches tiles for the target zoom level:
1906
+
1907
+ ```ts
1908
+ map.zoomTo(15, {
1909
+ experimental_preload: {},
1910
+ });
1911
+ ```
1912
+
1913
+ The `experimental_preload` object accepts these options:
1914
+
1915
+ | Option | Type | Default | Description |
1916
+ |---|---|---|---|
1917
+ | `maxTiles` | `number` | `512` | Maximum tiles to fetch. Tiles beyond this limit are silently dropped. |
1918
+ | `onProgress` | `(done, total, tileID?) => void` | — | Called after each tile fetch attempt (success or failure). |
1919
+ | `onError` | `(error) => void` | — | Called when a tile fails to load. |
1920
+
1921
+ #### Prefetching manually
1922
+
1923
+ Three methods let you prefetch tiles independently of camera animations.
1924
+
1925
+ **`experimental_preloadTilesForBounds`** — fetches all tiles within a bounding box across a zoom range:
1926
+
1927
+ ```ts
1928
+ await map.experimental_preloadTilesForBounds({
1929
+ bounds: map.getBounds(),
1930
+ minZoom: 8,
1931
+ maxZoom: 12,
1932
+ onProgress: (done, total) => console.log(`${done}/${total}`),
1933
+ });
1934
+ ```
1935
+
1936
+ **`experimental_preloadTilesForCameraPositions`** — fetches tiles visible from one or more camera viewpoints:
1937
+
1938
+ ```ts
1939
+ await map.experimental_preloadTilesForCameraPositions({
1940
+ positions: [
1941
+ { lng: -74.006, lat: 40.7128, zoom: 12 },
1942
+ { lng: -73.935, lat: 40.730, zoom: 14, pitch: 45 },
1943
+ ],
1944
+ maxTiles: 256,
1945
+ });
1946
+ ```
1947
+
1948
+ **`experimental_preloadTiles`** — fetches a specific list of tiles by ID (`"z/x/y"` format):
1949
+
1950
+ ```ts
1951
+ await map.experimental_preloadTiles({
1952
+ tileIDs: ["12/1205/1540", "12/1206/1540"],
1953
+ onError: (err) => console.error(err),
1954
+ });
1955
+ ```
1956
+
1957
+ #### Global config options
1958
+
1959
+ Two `config` properties tune the prefetching behaviour globally:
1960
+
1961
+ ```ts
1962
+ import { config } from "@maptiler/sdk";
1963
+
1964
+ // Number of camera positions sampled along a path for panTo/easeTo/fitBounds/zoomTo (default: 4)
1965
+ config.experimental_defaultPathSampleSteps = 6;
1966
+
1967
+ // Number of concurrent tile fetch workers (default: 4)
1968
+ config.experimental_defaultWorkerCount = 8;
1969
+ ```
1970
+
1846
1971
  ### Easy access to MapTiler API
1847
1972
 
1848
1973
  Our map SDK is not only about maps! We also provide plenty of wrappers to our API calls!
package/dist/Map.d.ts CHANGED
@@ -1,8 +1,9 @@
1
- import { default as maplibregl, StyleSpecification, MapOptions as MapOptionsML, ControlPosition, StyleSwapOptions, StyleOptions, RequestTransformFunction, LayerSpecification, SourceSpecification, CustomLayerInterface, FilterSpecification, StyleSetterOptions, ProjectionSpecification } from 'maplibre-gl';
1
+ import { default as maplibregl, StyleSpecification, MapOptions as MapOptionsML, ControlPosition, StyleSwapOptions, StyleOptions, RequestTransformFunction, LayerSpecification, SourceSpecification, CustomLayerInterface, FilterSpecification, StyleSetterOptions, ProjectionSpecification, FlyToOptions, EaseToOptions, FitBoundsOptions, AnimationOptions, LngLatBoundsLike, LngLatLike } from 'maplibre-gl';
2
2
  import { ReferenceMapStyle, MapStyleVariant } from '@maptiler/client';
3
3
  import { SdkConfig } from './config';
4
4
  import { LanguageInfo } from './language';
5
5
  import { MinimapOptionsInput } from './controls/Minimap';
6
+ import { PreloadTilesForBoundsOptions, PreloadTilesForCameraPositionsOptions, PreloadTilesOptions, WithTilePreload } from './tile-preloading/types';
6
7
  import { Telemetry } from './Telemetry';
7
8
  import { CubemapDefinition, CubemapLayer, CubemapLayerConstructorOptions } from './custom-layers/CubemapLayer';
8
9
  import { GradientDefinition, RadialGradientLayer, RadialGradientLayerConstructorOptions } from './custom-layers/RadialGradientLayer';
@@ -173,6 +174,14 @@ export type MapOptions = Omit<MapOptionsML, "style" | "maplibreLogo" | "attribut
173
174
  * Default is undefined, which means the plugin is enabled by default.
174
175
  */
175
176
  rtlTextPlugin?: boolean | string;
177
+ /**
178
+ * Whether to enable the experimental tile preloading feature.
179
+ * Default is false.
180
+ * @experimental
181
+ * @remarks
182
+ * **API Key Usage**: Each tile request counts against your MapTiler Cloud API key quota. Use with caution.
183
+ */
184
+ useExperimentalTilePreloading?: boolean;
176
185
  };
177
186
  /**
178
187
  * Options to provide to the {@link Map.setProjection} method
@@ -239,6 +248,7 @@ export declare class Map extends maplibregl.Map {
239
248
  getHalo(): RadialGradientLayer | undefined;
240
249
  setHalo(halo: GradientDefinition): void;
241
250
  private options;
251
+ private tilePreloader?;
242
252
  private isTerrainEnabled;
243
253
  private terrainExaggeration;
244
254
  private primaryLanguage;
@@ -532,4 +542,145 @@ export declare class Map extends maplibregl.Map {
532
542
  * and has never been changed.
533
543
  */
534
544
  isLanguageUpdated(): boolean;
545
+ /**
546
+ * Preloads all tiles within a geographic bounds across a range of zoom levels,
547
+ * storing them in the SDK tile cache so subsequent renders are served instantly.
548
+ *
549
+ * @remarks
550
+ * **API Key Usage**: This method issues one tile request per tile per active source.
551
+ * Tile count grows exponentially with zoom level — a wide zoom range over a large
552
+ * area can trigger thousands of requests, each counting against your MapTiler Cloud
553
+ * API key quota. Use narrow zoom ranges and small bounds wherever possible, and
554
+ * monitor consumption via the `onProgress` callback.
555
+ * @experimental
556
+ * @param {PreloadTilesForBoundsOptions} options - The options for the preload.
557
+ * @returns A promise that resolves when the preload is complete.
558
+ * @example
559
+ * ```ts
560
+ * await map.experimental_preloadTilesForBounds({
561
+ * bounds: map.getBounds(),
562
+ * minZoom: 8,
563
+ * maxZoom: 12,
564
+ * });
565
+ * ```
566
+ */
567
+ experimental_preloadTilesForBounds(options: PreloadTilesForBoundsOptions): Promise<void>;
568
+ /**
569
+ * Preloads tiles visible from each of the given camera positions, storing them
570
+ * in the SDK tile cache so renders at those viewpoints are served instantly.
571
+ *
572
+ * Use this method before a planned `flyTo` or `panTo` to ensure tiles along
573
+ * the path are ready when the animation reaches them.
574
+ * @experimental
575
+ * @param {PreloadTilesForCameraPositionsOptions} options - The options for the preload.
576
+ * @returns A promise that resolves when the preload is complete.
577
+ * @remarks
578
+ * **API Key Usage**: Each position triggers one request per visible tile per
579
+ * active source. More positions at higher zoom levels significantly increase
580
+ * API usage, each request counting against your MapTiler Cloud API key quota.
581
+ *
582
+ * @example
583
+ * ```ts
584
+ * await map.preloadTilesForCameraPositions({
585
+ * positions: [
586
+ * { lng: -74.006, lat: 40.7128, zoom: 12 },
587
+ * { lng: -73.935, lat: 40.730, zoom: 14 },
588
+ * ],
589
+ * onProgress: (done, total, tileID) => console.log(tileID),
590
+ * });
591
+ * ```
592
+ */
593
+ experimental_preloadTilesForCameraPositions(options: PreloadTilesForCameraPositionsOptions): Promise<void>;
594
+ /**
595
+ * Preloads a specific set of tiles identified by their `"z/x/y"` tile IDs,
596
+ * storing them in the SDK tile cache.
597
+ *
598
+ * @experimental
599
+ * @param {PreloadTilesOptions} options - The options for the preload.
600
+ * @returns A promise that resolves when the preload is complete.
601
+ * @remarks
602
+ * **API Key Usage**: Each tile ID results in one request per active source,
603
+ * counting against your MapTiler Cloud API key quota.
604
+ *
605
+ * @example
606
+ * ```ts
607
+ * await map.preloadTiles({
608
+ * tileIDs: ["12/1205/1540", "12/1206/1540"],
609
+ * onError: (err) => console.error(err),
610
+ * });
611
+ * ```
612
+ */
613
+ experimental_preloadTiles(options: PreloadTilesOptions): Promise<void>;
614
+ /**
615
+ * Changes any combination of center, zoom, bearing, and pitch, animating the
616
+ * transition along a curve that evokes flight. The animation seamlessly incorporates
617
+ * zooming and panning to help the user maintain her bearings even after traversing
618
+ * a great distance.
619
+ *
620
+ * If `options.experimental_preload` is provided, tiles along the flight path are fetched and
621
+ * cached before the animation begins so they are ready when rendered.
622
+ *
623
+ * @remarks
624
+ * **API Key Usage**: When `experimental_preload` is set, tile requests are issued for positions
625
+ * sampled along the flight path. These count against your MapTiler Cloud API key quota.
626
+ */
627
+ flyTo(options: WithTilePreload<FlyToOptions>, eventData?: object): this;
628
+ /**
629
+ * Pans the map to the specified location with an animated transition.
630
+ *
631
+ * If `options.experimental_preload` is provided, tiles along the pan path are fetched and
632
+ * cached before the animation begins.
633
+ *
634
+ * @remarks
635
+ * **API Key Usage**: When `experimental_preload` is set, tile requests are issued for positions
636
+ * sampled along the pan path. These count against your MapTiler Cloud API key quota.
637
+ */
638
+ panTo(lnglat: LngLatLike, options?: WithTilePreload<AnimationOptions & {
639
+ pitch?: number;
640
+ }>, eventData?: object): this;
641
+ /**
642
+ * Changes any combination of center, zoom, bearing, pitch, and roll, with an
643
+ * animated transition between old and new values.
644
+ *
645
+ * If `options.experimental_preload` is provided, tiles along the ease path are fetched and
646
+ * cached before the animation begins.
647
+ *
648
+ * @remarks
649
+ * **API Key Usage**: When `experimental_preload` is set, tile requests are issued for positions
650
+ * sampled along the ease path. These count against your MapTiler Cloud API key quota.
651
+ */
652
+ easeTo(options: WithTilePreload<EaseToOptions>, eventData?: object): this;
653
+ /**
654
+ * Pans and zooms the map to contain its visible area within the specified
655
+ * geographical bounds. This function will also reset the map's bearing to 0
656
+ * if options.bearing is not specified.
657
+ *
658
+ * If `options.experimental_preload` is provided, tiles for the target view are fetched and
659
+ * cached before the animation begins.
660
+ *
661
+ * @remarks
662
+ * **API Key Usage**: When `experimental_preload` is set, tile requests are issued for the
663
+ * destination viewport. These count against your MapTiler Cloud API key quota.
664
+ */
665
+ fitBounds(bounds: LngLatBoundsLike, options?: WithTilePreload<FitBoundsOptions>, eventData?: object): this;
666
+ /**
667
+ * Zooms the map to the specified zoom level, with an animated transition.
668
+ *
669
+ * If `options.experimental_preload` is provided, tiles for the target zoom level are fetched
670
+ * and cached before the animation begins.
671
+ *
672
+ * @remarks
673
+ * **API Key Usage**: When `experimental_preload` is set, tile requests are issued for the
674
+ * target zoom. These count against your MapTiler Cloud API key quota.
675
+ */
676
+ zoomTo(zoom: number, options?: WithTilePreload<AnimationOptions> | null, eventData?: object): this;
677
+ /**
678
+ * Returns the map's current camera state as a {@link CameraPosition}.
679
+ */
680
+ private currentCameraPosition;
681
+ /**
682
+ * Resolves camera method options into a {@link CameraPosition}, filling in
683
+ * current map state for any properties not specified in the options.
684
+ */
685
+ private resolveCameraPosition;
535
686
  }
@@ -1,15 +1,5 @@
1
1
  import { Feature, LineString, MultiLineString, MultiPoint, Polygon } from 'geojson';
2
2
  import { EasingFunctionName, Keyframe, NumericArrayWithNull } from './types';
3
- /**
4
- * Performs simple linear interpolation between two numbers.
5
- *
6
- * @param a - The start value
7
- * @param b - The end value
8
- * @param alpha - The interpolation factor (typically between 0 and 1):
9
- * 0 returns a, 1 returns b, and values in between return a proportional mix
10
- * @returns The interpolated value between a and b
11
- */
12
- export declare function lerp(a: number, b: number, alpha: number): number;
13
3
  /**
14
4
  * Interpolates an array of numbers, replacing null values with interpolated values.
15
5
  *
@@ -3,5 +3,5 @@ export { MaptilerAnimation };
3
3
  export type * from './MaptilerAnimation';
4
4
  export type * from './types';
5
5
  export * from './easing';
6
- export { type KeyframeableGeometry, type KeyframeableGeoJSONFeature, lerp, lerpArrayValues, parseGeoJSONFeatureToKeyframes, createBezierPathFromCoordinates, getAverageDistance, simplifyPath, resamplePath, stretchNumericalArray, } from './animation-helpers';
6
+ export { type KeyframeableGeometry, type KeyframeableGeoJSONFeature, lerpArrayValues, parseGeoJSONFeatureToKeyframes, createBezierPathFromCoordinates, getAverageDistance, simplifyPath, resamplePath, stretchNumericalArray, } from './animation-helpers';
7
7
  export type * from './animation-helpers';
package/dist/caching.d.ts CHANGED
@@ -1,4 +1,22 @@
1
1
  import { ResourceType } from 'maplibre-gl';
2
2
  export declare const CACHE_API_AVAILABLE: boolean;
3
3
  export declare function localCacheTransformRequest(reqUrl: URL, resourceType?: ResourceType): string;
4
+ /**
5
+ * Derives a stable cache key from a tile URL by stripping ephemeral params
6
+ * (`key`, `mtsid`) that vary per-request but do not affect tile content.
7
+ * Both the prefetch path and the protocol handler must use this function so
8
+ * cache writes and reads always resolve to the same key.
9
+ * @internal
10
+ */
11
+ export declare function getTileCacheKey(url: URL | string): string;
12
+ /**
13
+ * Fetches a tile URL and stores it in the SDK cache so subsequent MapLibre
14
+ * requests for the same tile are served from cache without a network round-trip.
15
+ *
16
+ * When the Cache API is unavailable, the tile is still fetched so the browser's
17
+ * own HTTP cache can serve it later.
18
+ *
19
+ * @internal
20
+ */
21
+ export declare function prefetchTileUrl(url: string, signal?: AbortSignal): Promise<void>;
4
22
  export declare function registerLocalCacheProtocol(): void;
package/dist/config.d.ts CHANGED
@@ -80,6 +80,15 @@ declare class SdkConfig extends EventEmitter {
80
80
  * Get the fetch fucntion
81
81
  */
82
82
  get fetch(): FetchFunction | null;
83
+ /**
84
+ * The default number of steps to sample for the experimental flyTo path preloading.
85
+ */
86
+ private _experimentalDefaultPathSampleSteps;
87
+ get experimental_defaultPathSampleSteps(): number;
88
+ set experimental_defaultPathSampleSteps(s: number);
89
+ private _experimentalDefaultWorkerCount;
90
+ get experimental_defaultWorkerCount(): number;
91
+ set experimental_defaultWorkerCount(w: number);
83
92
  }
84
93
  declare const config: SdkConfig;
85
94
  export { config, SdkConfig };
package/dist/index.d.ts CHANGED
@@ -84,6 +84,7 @@ export { MapTouchEvent } from './MLAdapters/MapTouchEvent';
84
84
  export { MapMouseEvent } from './MLAdapters/MapMouseEvent';
85
85
  export * from './ml-types';
86
86
  export { Map, GeolocationType, type AttributionControlOptions, type MapOptions, type LoadWithTerrainEvent } from './Map';
87
+ export type { CameraPosition, TilePreloadOptions, WithTilePreload, PreloadTilesForBoundsOptions, PreloadTilesForCameraPositionsOptions, PreloadTilesOptions, TilePreloadErrorCallback, TilePreloadProgressCallback, } from './tile-preloading';
87
88
  export { type BaseGeocodingOptions, type ByIdGeocodingOptions, type CommonForwardAndReverseGeocodingOptions, type GeocodingOptions, type LanguageGeocodingOptions, type ReverseGeocodingOptions, geocoding, } from './geocoding';
88
89
  export * from './controls';
89
90
  export { type AutomaticStaticMapOptions, type BoundedStaticMapOptions, type BufferToPixelDataFunction, type CenteredStaticMapOptions, type CoordinateExport, type CoordinateGrid, type CoordinateId, type CoordinateSearch, type CoordinateSearchResult, type CoordinateTransformResult, type CoordinateTransformation, type Coordinates, type CoordinatesSearchOptions, type CoordinatesTransformOptions, type DefaultTransformation, type ElevationAtOptions, type ElevationBatchOptions, type FeatureHierarchy, type FetchFunction, type GeocodingFeature, type GeocodingSearchResult, type GeolocationInfoOptions, type GeolocationResult, type GetDataOptions, MapStyle, type MapStylePreset, type MapStyleType, MapStyleVariant, type PixelData, ReferenceMapStyle, ServiceError, type StaticMapBaseOptions, type StaticMapMarker, type TileJSON, type XYZ, bufferToPixelDataBrowser, circumferenceAtLatitude, coordinates, data, elevation, expandMapStyle, geolocation, getBufferToPixelDataParser, getTileCache, mapStylePresetList, math, misc, staticMaps, styleToStyle, type LanguageInfo, areSameLanguages, toLanguageInfo, isLanguageInfo, getAutoLanguage, getLanguageInfoFromFlag, getLanguageInfoFromCode, getLanguageInfoFromKey, canParsePixelData, } from '@maptiler/client';