@maptiler/client 3.2.0-rc.4 → 3.2.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 (2) hide show
  1. package/package.json +1 -1
  2. package/readme.md +270 -74
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maptiler/client",
3
- "version": "3.2.0-rc.4",
3
+ "version": "3.2.0",
4
4
  "description": "Javascript & Typescript wrapper to MapTiler Cloud API",
5
5
  "module": "dist/maptiler-client.mjs",
6
6
  "types": "dist/maptiler-client.d.ts",
package/readme.md CHANGED
@@ -3,12 +3,14 @@
3
3
  # API Client Library for JavaScript / TypeScript
4
4
 
5
5
  The **MapTiler Client JS** exposes a number of handy functions that wrap API calls to [MapTiler Cloud API services](https://docs.maptiler.com/cloud/api), such as:
6
+
6
7
  - [Geocoding forward and reverse](#-geocoding)
7
8
  - [Geolocation from visitor's IP address](#%EF%B8%8F%E2%80%8D%EF%B8%8F-geolocation)
8
9
  - [Coordinate systems search and transform](#-coordinates)
9
10
  - [User data fetching as GeoJSON](#-data)
10
11
  - [Static maps of all sorts](#%EF%B8%8F-static-maps)
11
12
  - [Elevation lookup with batch features](#%EF%B8%8F-elevation)
13
+ - [Routing directions for car, truck, bicycle and pedestrian](#-routing)
12
14
 
13
15
  The project is entirely written in TypeScript and all the function arguments are nicely documented and typed.
14
16
 
@@ -20,8 +22,7 @@ The project is entirely written in TypeScript and all the function arguments are
20
22
  - Runs: in Node.js or in browser
21
23
  - Open source license
22
24
 
23
- [![](https://img.shields.io/npm/v/@maptiler/client?style=for-the-badge&labelColor=D3DBEC&color=f2f6ff&logo=npm&logoColor=333359)](https://www.npmjs.com/package/@maptiler/client) ![](https://img.shields.io/badge/-white?style=for-the-badge&logo=javascript)![](https://img.shields.io/badge/-white?style=for-the-badge&logo=typescript)
24
- ---
25
+ ## [![](https://img.shields.io/npm/v/@maptiler/client?style=for-the-badge&labelColor=D3DBEC&color=f2f6ff&logo=npm&logoColor=333359)](https://www.npmjs.com/package/@maptiler/client) ![](https://img.shields.io/badge/-white?style=for-the-badge&logo=javascript)![](https://img.shields.io/badge/-white?style=for-the-badge&logo=typescript)
25
26
 
26
27
  📖 [Documentation](https://docs.maptiler.com/cloud/api/)   📦 [NPM Package](https://www.npmjs.com/package/@maptiler/client)   🌐 [Website](https://docs.maptiler.com/client-js/)   🔑 [Get API Key](https://cloud.maptiler.com/account/keys/)
27
28
 
@@ -54,19 +55,20 @@ npm install --save @maptiler/client
54
55
  ```
55
56
 
56
57
  ### From NodeJS
57
- NodeJS includes a stable `fetch()` function only from version *18*, and this client does not contain a polyfill. If the `fetch()` function exists (browser or Node >= 18) then it is going to be resolved automatically. Yet, a custom `fetch()` function can be provided to the `config` object for Node < 18.
58
58
 
59
- In [this NodeJS example](examples/test-node.js), you can see that the package [Node Fetch](https://www.npmjs.com/package/node-fetch) has been `npm install`ed and is passed to the config object of the *MapTiler Client*.
59
+ NodeJS includes a stable `fetch()` function only from version _18_, and this client does not contain a polyfill. If the `fetch()` function exists (browser or Node >= 18) then it is going to be resolved automatically. Yet, a custom `fetch()` function can be provided to the `config` object for Node < 18.
60
+
61
+ In [this NodeJS example](https://github.com/maptiler/maptiler-client-js/blob/main/examples/test-node.js), you can see that the package [Node Fetch](https://www.npmjs.com/package/node-fetch) has been `npm install`ed and is passed to the config object of the _MapTiler Client_.
60
62
 
61
63
  ```js
62
64
  import {
63
65
  config,
64
66
  // ...
65
- } from '@maptiler/client';
67
+ } from "@maptiler/client";
66
68
 
67
69
  // For this example to work, you must bring your own node-compatible fetch,
68
70
  // unles you are using a version of Nodejs that already contains fetch (>=18)
69
- import fetch from 'node-fetch';
71
+ import fetch from "node-fetch";
70
72
 
71
73
  config.fetch = fetch;
72
74
 
@@ -79,7 +81,7 @@ config.fetch = fetch;
79
81
 
80
82
  ```ts
81
83
  // Import the whole library
82
- import * as maptilerClient from '@maptiler/client';
84
+ import * as maptilerClient from "@maptiler/client";
83
85
 
84
86
  // Or import only the bits you need
85
87
  import {
@@ -90,8 +92,9 @@ import {
90
92
  data,
91
93
  staticMaps,
92
94
  elevation,
95
+ routing,
93
96
  math,
94
- } from '@maptiler/client';
97
+ } from "@maptiler/client";
95
98
  ```
96
99
 
97
100
  <br>
@@ -106,7 +109,7 @@ The [examples](examples/) folder includes usages for **NodeJS**, **browser with
106
109
 
107
110
  For detailed guides, API reference, and advanced examples, visit our comprehensive documentation:
108
111
 
109
- [API documentation](https://docs.maptiler.com/cloud/api/)
112
+ [API documentation](https://docs.maptiler.com/client-js/api/)
110
113
 
111
114
  ### Easy access to MapTiler API
112
115
 
@@ -116,35 +119,47 @@ Here is the list of service wrapper functions that are built-in:
116
119
 
117
120
  > ✅ Please, use geocoding functions only from client-side (browser) and do not 🚫 **store** or **redistribute** MapTiler Cloud API data. In case of doubt, consult the [terms](https://www.maptiler.com/cloud/terms/#explicitly-prohibited-use) ⚖️
118
121
 
119
- Read more about geocoding, including forward, reverse, batch, and usage examples, in our [Geocoding API documentation](https://docs.maptiler.com/cloud/api/geocoding/).
120
-
121
122
  #### Forward
122
123
 
123
124
  You want to know the longitude and latitude of a specific place, use the forward geocoding:
125
+
124
126
  ```ts
125
127
  // in an async function, or as a 'thenable':
126
- const result = await maptilerClient.geocoding.forward('paris');
128
+ const result = await maptilerClient.geocoding.forward("paris");
127
129
  ```
130
+
128
131
  You can provide some options, such as:
132
+
129
133
  - the proximity, given a lon-lat position, to sort the results
130
134
  - one of more languages to get the results into
131
135
  - a bounding geo box, to restrict the search to a given window
132
136
 
137
+ Read more about forward geocoding, as well as feature ID query and batch forward geocoding, on our [official documentation](https://docs.maptiler.com/client-js/api/variables/services_geocoding.geocoding/#forward).
138
+
133
139
  #### Reverse
134
140
 
135
141
  You want to know the name of a place, given a longitude-latitude? Use the reverse geocoding:
142
+
136
143
  ```ts
137
144
  // in an async function, or as a 'thenable':
138
145
  const result = await maptilerClient.geocoding.reverse([6.249638, 46.402056]);
139
146
  ```
147
+
140
148
  The same option object as the forward geocoding can be provided.
141
149
 
150
+ Read more about reverse geocoding on our [official documentation](https://docs.maptiler.com/client-js/api/variables/services_geocoding.geocoding/#reverse).
151
+
142
152
  #### Language
143
153
 
144
- For both *forward* and *reverse* geocoding, this library provides a list of supported languages as shorthands that include [ISO language codes](https://en.wikipedia.org/wiki/ISO_639-1). The result will be provided in multiple languages if the `language` options are an array:
154
+ For both _forward_ and _reverse_ geocoding, this library provides a list of supported languages as shorthands that include [ISO language codes](https://en.wikipedia.org/wiki/ISO_639-1). The result will be provided in multiple languages if the `language` options are an array:
145
155
 
146
156
  ```ts
147
- const result = await maptilerClient.geocoding.forward('paris', {language: [maptilerClient.Language.SPANISH, maptilerClient.geocoding.Language.KOREAN]})
157
+ const result = await maptilerClient.geocoding.forward("paris", {
158
+ language: [
159
+ maptilerClient.Language.SPANISH,
160
+ maptilerClient.geocoding.Language.KOREAN,
161
+ ],
162
+ });
148
163
  ```
149
164
 
150
165
  The special language `AUTO` will detect the platform/browser preferred language.
@@ -158,11 +173,14 @@ The geolocation service provides location information of a visitor using its IP
158
173
  The geolocation uses the IP address of a visitor to provide information about their location, such as city, region, country, timezone, etc. The precision is lower than GPS, but it does not require visitors to explicitly enable the location service from their web browser.
159
174
 
160
175
  There is only a single function:
176
+
161
177
  ```ts
162
178
  // in an async function, or as a 'thenable':
163
179
  const result = await maptilerClient.geolocation.info();
164
180
  ```
165
181
 
182
+ Read more about geolocation on our [official documentation](https://docs.maptiler.com/client-js/api/variables/services_geolocation.geolocation/).
183
+
166
184
  ### 🌐 Coordinates
167
185
 
168
186
  If you are already familiar with [epsg.io](https://epsg.io/) (created by MapTiler), then you may find it convenient to access the details of more than 10 thousands of coordinate reference systems (CRS) programmatically, as well as transforming coordinates from one system to another!
@@ -170,6 +188,7 @@ If you are already familiar with [epsg.io](https://epsg.io/) (created by MapTile
170
188
  #### Search
171
189
 
172
190
  The `search` lets you perform a query in a free form fashion. Here are some examples:
191
+
173
192
  ```ts
174
193
  // in an async function, or as a 'thenable':
175
194
  const resultA = await maptilerClient.coordinates.search('mercator');
@@ -180,6 +199,8 @@ const resultD = await maptilerClient.coordinates.search('code:4326', {transforma
180
199
 
181
200
  The `transformations` options retrieve a lot more details about the CRS that MapTiler API is able to transform to/from than just their IDs.
182
201
 
202
+ Read more about searching coordinate systems in our [official documentation](https://docs.maptiler.com/client-js/api/variables/services_coordinates.coordinates/#search).
203
+
183
204
  #### Transform
184
205
 
185
206
  Transforming a couple of coordinates from one system to another can be challenging, for example, most countries have their own official system, yet web mapping tools are more often than not exclusive to [WGS84](https://epsg.io/4326).
@@ -190,35 +211,48 @@ If not provided, both the source (`sourceCrs`) and the destination (`targetCrs`)
190
211
  // in an async function, or as a 'thenable':
191
212
 
192
213
  // Providing one coordinate to transform, with a target CRS being EPSG:9793 (RGF93 v2 / Lambert-93, France official CRS)
193
- const resultA = await maptilerClient.coordinates.transform([1, 45], {targetCrs: 9793})
214
+ const resultA = await maptilerClient.coordinates.transform([1, 45], {
215
+ targetCrs: 9793,
216
+ });
194
217
 
195
218
  // Using the same logic, we can pass up to 50 coordinates to be transformed
196
- const resultB = await maptilerClient.coordinates.transform([[10, 48], [1, 45]], {targetCrs: 9793})
219
+ const resultB = await maptilerClient.coordinates.transform(
220
+ [
221
+ [10, 48],
222
+ [1, 45],
223
+ ],
224
+ { targetCrs: 9793 },
225
+ );
197
226
  ```
198
227
 
228
+ Read more about transforming coordinates on our [official documentation](https://docs.maptiler.com/client-js/api/variables/services_coordinates.coordinates/#transform).
229
+
199
230
  ### 💽 Data
200
231
 
201
- MapTiler Cloud give its users the possibility to [upload and create data](https://cloud.maptiler.com/data/), manually with a user interface or by uploading a GPX, GeoJSON, KML or shp file. A unique ID is associated with each dataset so that we can later on access it programmatically to retrieve a GeoJSON equivalent of it:
232
+ MapTiler Cloud give its users the possibility to [upload and create data](https://cloud.maptiler.com/data/), manually with a user interface or by uploading a GPX, GeoJSON, KML or zipped SHP file. A unique ID is associated with each dataset so that we can later on access it programmatically to retrieve a GeoJSON equivalent of it:
202
233
 
203
234
  ```ts
204
235
  // in an async function, or as a 'thenable':
205
- const result = await maptilerClient.data.get('my-dataset-unique-id')
236
+ const result = await maptilerClient.data.get("my-dataset-unique-id");
206
237
  ```
207
238
 
208
239
  Since the result is a GeoJSON, it can easily be added to a `map` with `.addSource()` and `.addLayer()`.
209
240
 
241
+ Read more about fetching your own data on our [official documentation](https://docs.maptiler.com/client-js/api/variables/services_data.data/).
242
+
210
243
  ### 🗺️ Static maps
211
244
 
212
245
  > ✅ Please, use static maps URLs only from client side `<img>` elements, and do not 🚫 store or redistribute the static map files. In case of doubt, consult the [terms](https://www.maptiler.com/cloud/terms/#explicitly-prohibited-use) ⚖️
213
246
 
214
247
  Maptiler Cloud provides many possibilities for creating static maps as PNG, JPEG or WebP images. They all offer the possibilities to:
248
+
215
249
  - Choose from one of the MapTiler styles or your own
216
250
  - Add markers with a custom icon (or default icon with custom color)
217
251
  - Add path or polygon, with a parametric line width and color and a parametric filling color
218
252
 
219
253
  Three modes are available: `centered`, `bounded` and `automatic`.
220
254
 
221
- > 📣 *__important:__* <span style="text-decoration: underline">only image **URLs** are returned.</span>
255
+ > 📣 _**important:**_ <span style="text-decoration: underline">only image **URLs** are returned.</span>
222
256
  > Contrary to the other functions of this library, the static map functions **do not** perform any query to MapTiler Cloud API, instead they build the image URL for you to use in `<img>` elements.
223
257
 
224
258
  #### Map Styles
@@ -239,9 +273,9 @@ In the following static map functions, the `option` object features a `style` pr
239
273
  - `MapStyle.WINTER` reference style for winter adventure
240
274
  - `MapStyle.SATELLITE` reference style satellite and airborne imagery (no variants)
241
275
  - `MapStyle.HYBRID` reference style satellite and airborne imagery with labels (no variants)
242
- - `MapStyle.BASIC` reference style for minimalist design and general purpose
243
- - `MapStyle.BASIC.DARK` (variant)
244
- - `MapStyle.BASIC.LIGHT` (variant)
276
+ - `MapStyle.BASE` reference style for minimalist design and general purpose
277
+ - `MapStyle.BASE.DARK` (variant)
278
+ - `MapStyle.BASE.LIGHT` (variant)
245
279
  - `MapStyle.BRIGHT` reference style for high contrast navigation
246
280
  - `MapStyle.BRIGHT.DARK` (variant)
247
281
  - `MapStyle.BRIGHT.LIGHT` (variant)
@@ -254,7 +288,7 @@ In the following static map functions, the `option` object features a `style` pr
254
288
  - `MapStyle.VOYAGER.DARK` (variant)
255
289
  - `MapStyle.VOYAGER.LIGHT` (variant)
256
290
  - `MapStyle.VOYAGER.VINTAGE` (variant)
257
- - `MapStyle.TONER` reference style for very high contrast stylish maps
291
+ - `MapStyle.TONER` reference style for very high contrast stylish maps
258
292
  - `MapStyle.TONER.BACKGROUND` (variant)
259
293
  - `MapStyle.TONER.LITE` (variant)
260
294
  - `MapStyle.TONER.LINES` (variant)
@@ -269,11 +303,11 @@ Note that if a path or markers are provided, the framing of the map will not aut
269
303
  ```ts
270
304
  const imageLink = maptilerClient.staticMaps.centered(
271
305
  // center position (Boston)
272
- [-71.06080, 42.362114],
306
+ [-71.0608, 42.362114],
273
307
 
274
308
  // zoom level
275
- 12.5,
276
-
309
+ 12.5,
310
+
277
311
  // Options
278
312
  {
279
313
  // Request a hiDPI/Retina image
@@ -285,10 +319,11 @@ const imageLink = maptilerClient.staticMaps.centered(
285
319
 
286
320
  // Map style
287
321
  style: maptilerClient.MapStyle.OUTDOOR,
288
- });
322
+ },
323
+ );
289
324
  ```
290
325
 
291
- Read more about centered static maps in our official [Static maps API documentation](https://docs.maptiler.com/cloud/api/static-maps/#center-based-image).
326
+ Read more about centered static maps on our [official documentation](https://docs.maptiler.com/client-js/api/variables/services_staticMaps.staticMaps/#centered).
292
327
 
293
328
  #### Bounded static maps
294
329
 
@@ -298,10 +333,10 @@ This type of map requires a bounding box made of two points: the south-west boun
298
333
  const imageLink = maptilerClient.staticMaps.bounded(
299
334
  // The bounding box on Europe
300
335
  [
301
- -24, // west bound (min x)
336
+ -24, // west bound (min x)
302
337
  34.5, // south bound (min y)
303
- 32, // east bound (max x)
304
- 71, // north bound (max y)
338
+ 32, // east bound (max x)
339
+ 71, // north bound (max y)
305
340
  ],
306
341
 
307
342
  // Options
@@ -313,25 +348,24 @@ const imageLink = maptilerClient.staticMaps.bounded(
313
348
 
314
349
  // Extra space that will be added around the bounding box, in percentage
315
350
  // (0.1 = 10% is actually the default)
316
- padding: 0.1
317
- });
351
+ padding: 0.1,
352
+ },
353
+ );
318
354
  ```
319
355
 
320
356
  Since the zoom level cannot be provided, the level of detail is dictated by the size of the output image. Here is an example:
321
357
 
322
- | `2048 x 2048` | `1024 x 1024` |
323
- | :-----------: | :-----------: |
324
- | ![](images/screenshots/static-bounded-europe-2048.png) | ![](images/screenshots/static-bounded-europe-1024.png) |
358
+ | `2048 x 2048` | `1024 x 1024` |
359
+ | :-----------------------------------------------------: | :-----------------------------------------------------: |
360
+ | ![](images/screenshots/static-bounded-europe-2048.webp) | ![](images/screenshots/static-bounded-europe-1024.webp) |
325
361
 
326
362
  As you may notice, the geo bounding box could have very different proportions than the output image size. In the following example, we place the very same bounding box around Portugal, which has a this particular strip looking shape. We also add a `path` that repeats exactly the same bounding box to show the difference between the provided bounding box and the final image. We kept the default padding of 10%:
327
363
 
364
+ | `2048 x 2048` | `1024 x 2048` |
365
+ | :------------------------------------------------------------: | :------------------------------------------------------------: |
366
+ | ![](images/screenshots/static-bounded-portugal-2048x2048.webp) | ![](images/screenshots/static-bounded-portugal-1024x2048.webp) |
328
367
 
329
- | `2048 x 2048` | `1024 x 2048` |
330
- | :-----------: | :-----------: |
331
- | ![](images/screenshots/static-bounded-portugal-2048x2048.png) | ![](images/screenshots/static-bounded-portugal-1024x2048.png) |
332
-
333
-
334
- Read more about bounded static maps on our official [API documentation](https://docs.maptiler.com/cloud/api/static-maps/#bounds-based-image).
368
+ Read more about bounded static maps on our [official documentation](https://docs.maptiler.com/client-js/api/variables/services_staticMaps.staticMaps/#bounded).
335
369
 
336
370
  #### Automatic static maps
337
371
 
@@ -341,11 +375,14 @@ In the following example, we are going to load a cycling track recorded by one o
341
375
 
342
376
  ```ts
343
377
  // Fetching the GeoJSON
344
- const bikeTrack = await maptilerClient.data.get('the-id-of-a-bike-track-in-montreal');
378
+ const bikeTrack = await maptilerClient.data.get(
379
+ "the-id-of-a-bike-track-in-montreal",
380
+ );
345
381
 
346
382
  // Extracting the track points with the shape [[lng, lat], [lng, lat], ...]
347
- const trackPoints = bikeTrack.features[0].geometry.coordinates[0]
348
- .map(p => p.slice(0, 2));
383
+ const trackPoints = bikeTrack.features[0].geometry.coordinates[0].map((p) =>
384
+ p.slice(0, 2),
385
+ );
349
386
 
350
387
  const imageLink = maptilerClient.staticMaps.automatic({
351
388
  // hiDPI/Retina precision
@@ -353,7 +390,7 @@ const imageLink = maptilerClient.staticMaps.automatic({
353
390
 
354
391
  // A fairly large output image
355
392
  width: 2048,
356
- height: 1024 ,
393
+ height: 1024,
357
394
 
358
395
  // A grey style on which the track will pop!
359
396
  style: maptilerClient.MapStyle.STREETS.LIGHT,
@@ -362,20 +399,20 @@ const imageLink = maptilerClient.staticMaps.automatic({
362
399
  path: trackPoints,
363
400
 
364
401
  // Adding a marker for the starting point, with a custom color (array of shape [lng, lat, color])
365
- marker: [trackPoints[0][0], trackPoints[0][1], '#0a0'],
402
+ marker: [trackPoints[0][0], trackPoints[0][1], "#0a0"],
366
403
 
367
404
  // Showing the track in red
368
- pathStrokeColor: 'red',
405
+ pathStrokeColor: "red",
369
406
  });
370
407
  ```
371
408
 
372
409
  And voila!
373
410
 
374
- ![static map with bike path](images/screenshots/static-with-path.png)
411
+ ![static map with bike path](images/screenshots/static-with-path.webp)
375
412
 
376
- > 📣 *__Note:__* The GeoJSON for this track contains 9380 pairs of coordinates, which is a lot! In order to send the track to MapTiler Cloud static maps API, the client simplifies the long paths while keeping a high degree of precision using a very fast [Ramer-Douglas-Peucker algorithm](https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm).
413
+ > 📣 _**Note:**_ The GeoJSON for this track contains 9380 pairs of coordinates, which is a lot! In order to send the track to MapTiler Cloud static maps API, the client simplifies the long paths while keeping a high degree of precision using a very fast [Ramer-Douglas-Peucker algorithm](https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm).
377
414
 
378
- Read more about bounded static maps on our official [API documentation](https://docs.maptiler.com/cloud/api/static-maps/#auto-fitted-image).
415
+ Read more about automatic bounded static maps on our [official documentation](https://docs.maptiler.com/client-js/api/variables/services_staticMaps.staticMaps/#automatic).
379
416
 
380
417
  ### 🏔️ Elevation
381
418
 
@@ -383,7 +420,7 @@ With the elevation API, it's possible to get the elevation in meters from any lo
383
420
 
384
421
  > ℹ️ Under the hood, the elevation API is fueled by MapTiler Cloud's **RGB Terrain** raster tileset, which is a composite of many high-resolution DEMs from all over the world, curated and processed by our geodata team! The same dataset is also fueling our SDK's elevation (3D terrain) and the hillshading we use in many of our styles.
385
422
 
386
- > 📣 Note for **TypeScript** users: internally, the elevation feature relies on some *GeoJSON* type definitions that can be found in this NPM package: `@types/geojson`. Namely `LineString`, `MultiLineString` and `Position`. It may improve your developer experience to also use these types.
423
+ > 📣 Note for **TypeScript** users: internally, the elevation feature relies on some _GeoJSON_ type definitions that can be found in this NPM package: `@types/geojson`. Namely `LineString`, `MultiLineString` and `Position`. It may improve your developer experience to also use these types.
387
424
 
388
425
  Let's see how to use it:
389
426
 
@@ -396,7 +433,10 @@ import { Position } from "geojson";
396
433
  const montBlancPeak: Position = [6.864884, 45.832743];
397
434
  const elevatedPosition = await maptilerClient.elevation.at(montBlancPeak);
398
435
  ```
399
- The returned value is also a *GeoJSON* `Position` array, but with three elements: `[lng, lat, elevation]`.
436
+
437
+ The returned value is also a _GeoJSON_ `Position` array, but with three elements: `[lng, lat, elevation]`.
438
+
439
+ Read more about elevation lookup for a single location in our [official documentation](https://docs.maptiler.com/client-js/api/variables/services_elevation.elevation/#at).
400
440
 
401
441
  #### Batch mode
402
442
 
@@ -405,67 +445,221 @@ The returned value is also a *GeoJSON* `Position` array, but with three elements
405
445
  import { Position } from "geojson";
406
446
 
407
447
  const peaks: Position[] = [
408
- [6.864884, 45.832743], // Mont Blanc, Alps
409
- [86.9250, 27.9881], // Mount Everest, Himalayas
410
- [-70.0109, -32.6532], // Aconcagua, Andes
411
- [-151.0064, 63.0695], // Denali, Alaska
412
- [37.3556, -3.0674], // Mount Kilimanjaro
413
- [42.4453, 43.3499], // Mount Elbrus, Caucasus
414
- [137.1595, -4.0784], // Puncak Jaya, Sudirman Range
415
- [-140.4055, 60.5672], // Mount Logan, Saint Elias Mountains
416
- [138.73111, 35.358055], // Mount Fuji
448
+ [6.864884, 45.832743], // Mont Blanc, Alps
449
+ [86.925, 27.9881], // Mount Everest, Himalayas
450
+ [-70.0109, -32.6532], // Aconcagua, Andes
451
+ [-151.0064, 63.0695], // Denali, Alaska
452
+ [37.3556, -3.0674], // Mount Kilimanjaro
453
+ [42.4453, 43.3499], // Mount Elbrus, Caucasus
454
+ [137.1595, -4.0784], // Puncak Jaya, Sudirman Range
455
+ [-140.4055, 60.5672], // Mount Logan, Saint Elias Mountains
456
+ [138.73111, 35.358055], // Mount Fuji
417
457
  ];
418
458
 
419
459
  const elevatedPeaks = await maptilerClient.elevation.batch(peaks);
420
460
  ```
421
461
 
462
+ Read more about elevation lookup for a batch of locations in our [official documentation](https://docs.maptiler.com/client-js/api/variables/services_elevation.elevation/#batch).
463
+
422
464
  #### From a GeoJSON LineString
423
465
 
424
- In the *GeoJSON* LineString case, it clones the entire structure and the positions arrays of the clone will contain three elements: `[lng, lat, elevation]`. The original LineString is not mutated nor pointed at.
466
+ In the _GeoJSON_ LineString case, it clones the entire structure and the positions arrays of the clone will contain three elements: `[lng, lat, elevation]`. The original LineString is not mutated nor pointed at.
425
467
 
426
468
  ```ts
427
469
  // Not mandatory, but it's to explain where the type comes from:
428
470
  import { LineString } from "geojson";
429
471
 
430
-
431
472
  const someLineString: LineString = {
432
473
  type: "LineString",
433
- coordinates: [[6.864884, 45.832743], [86.9250, 27.9881], [-70.0109, -32.6532]]
474
+ coordinates: [
475
+ [6.864884, 45.832743],
476
+ [86.925, 27.9881],
477
+ [-70.0109, -32.6532],
478
+ ],
434
479
  };
435
480
 
436
- const someElevatedLineString = await maptilerClient.elevation.fromLineString(someLineString);
481
+ const someElevatedLineString =
482
+ await maptilerClient.elevation.fromLineString(someLineString);
437
483
  // someElevatedLineString is also of type LineString
438
484
  ```
439
485
 
486
+ Read more about elevation lookup for a `LineString` in our [official documentation](https://docs.maptiler.com/client-js/api/variables/services_elevation.elevation/#fromlinestring).
487
+
440
488
  #### From a GeoJSON MultiLineString
441
489
 
442
- In the *GeoJSON* MultiLineString case, it clones the entire structure and the positions arrays of the clone will contain three elements: `[lng, lat, elevation]`. The original MultiLineString is not mutated nor pointed at.
490
+ In the _GeoJSON_ MultiLineString case, it clones the entire structure and the positions arrays of the clone will contain three elements: `[lng, lat, elevation]`. The original MultiLineString is not mutated nor pointed at.
443
491
 
444
492
  ```ts
445
493
  // Not mandatory, but it's to explain where the type comes from:
446
494
  import { MultiLineString } from "geojson";
447
495
 
448
-
449
496
  const someMultiLineString: MultiLineString = {
450
497
  type: "LineString",
451
498
  coordinates: [
452
- [[6.864884, 45.832743], [86.9250, 27.9881], [-70.0109, -32.6532]],
453
- [[-151.0064, 63.0695], [37.3556, -3.0674], [42.4453, 43.3499]],
454
- [[137.1595, -4.0784], [-140.4055, 60.5672], [138.73111, 35.358055]],
455
- ]
499
+ [
500
+ [6.864884, 45.832743],
501
+ [86.925, 27.9881],
502
+ [-70.0109, -32.6532],
503
+ ],
504
+ [
505
+ [-151.0064, 63.0695],
506
+ [37.3556, -3.0674],
507
+ [42.4453, 43.3499],
508
+ ],
509
+ [
510
+ [137.1595, -4.0784],
511
+ [-140.4055, 60.5672],
512
+ [138.73111, 35.358055],
513
+ ],
514
+ ],
456
515
  };
457
516
 
458
- const someElevatedMultiLineString = await maptilerClient.elevation.fromMultiLineString(someMultiLineString);
517
+ const someElevatedMultiLineString =
518
+ await maptilerClient.elevation.fromMultiLineString(someMultiLineString);
459
519
  // someElevatedMultiLineString is also of type MultiLineString
460
520
  ```
461
521
 
522
+ Read more about elevation lookup for a `MultiLineString` in our [official documentation](https://docs.maptiler.com/client-js/api/variables/services_elevation.elevation/#frommultilinestring).
523
+
462
524
  #### Caching
463
525
 
464
526
  In order to increase performance while reducing unnecessary elevation data fetching, the elevation tiles are cached. This is particularly important for the LineString and MultiLineString lookups because GeoJSON data are likely to come from a recorded or planned route, where position points are very close to one another.
465
527
 
528
+ ### 🧭 Routing
529
+
530
+ The `routing` module wraps the MapTiler Routing API, with a set of functions for each of its services. All of them share the same [request options and error handling](#request-options-and-errors).
531
+
532
+ #### Directions
533
+
534
+ The directions service computes a route between two or more locations, by car, truck, bicycle or on foot. The response contains a summary of the route (travel time, distance, bounding box), the geometry of each leg between waypoints and turn-by-turn steps with navigation instructions.
535
+
536
+ Directions are available with both HTTP methods: `directionsPost` supports every feature of the API, and `directionsGet` sends the request as URL query parameters, with a few features left out.
537
+
538
+ ##### Using POST
539
+
540
+ The only mandatory parts are the `profile` (`car`, `truck`, `bicycle` or `pedestrian`) and at least two `locations`:
541
+
542
+ ```ts
543
+ // in an async function, or as a 'thenable':
544
+ const result = await maptilerClient.routing.directionsPost({
545
+ profile: "car",
546
+ locations: [
547
+ { lon: 14.4213, lat: 50.0875 }, // Prague
548
+ { lon: 16.6068, lat: 49.1951 }, // Brno
549
+ ],
550
+ });
551
+
552
+ // Travel time in seconds and distance in the response units
553
+ const { totalTime, totalLength } = result.route.summary;
554
+ ```
555
+
556
+ You can provide many more options, such as:
557
+
558
+ - the `profileOptions` matching the chosen profile, e.g. the car routing mode (fastest, shortest or balanced), the truck dimensions and weight, the bicycle type or the walking speed
559
+ - `avoidances` of toll roads, ferries or highways, as part of the car and truck `profileOptions`
560
+ - either a `departureTime` or an `arrivalTime`
561
+ - a `heading` (preferred direction of travel) and a `waypoint` flag on each location
562
+ - `avoidLocations`, a GeoJSON `MultiPoint` or `MultiPolygon` of places the route must not go through
563
+ - `response` options: distance units (`km` or `mi`), language of the instructions, number of alternate routes (up to 3) and the level of detail (`legs`, `steps` or `instructions`)
564
+
565
+ ```ts
566
+ const result = await maptilerClient.routing.directionsPost({
567
+ profile: "truck",
568
+ profileOptions: {
569
+ height: 4,
570
+ weight: 18,
571
+ hazmat: true,
572
+ avoidances: { tolls: true },
573
+ },
574
+ locations: [
575
+ { lon: 14.4213, lat: 50.0875 },
576
+ { lon: 16.6068, lat: 49.1951 },
577
+ ],
578
+ departureTime: "2026-12-01T08:00",
579
+ response: {
580
+ units: "km",
581
+ language: "en",
582
+ alternates: 2,
583
+ additionalData: { detailLevel: "instructions" },
584
+ },
585
+ });
586
+
587
+ // Turn-by-turn instructions of the first leg
588
+ for (const step of result.route.legs[0].steps ?? []) {
589
+ console.log(step.maneuver?.instruction);
590
+ }
591
+
592
+ // Alternate routes have the same shape as the main route
593
+ const alternateRoutes = result.alternates ?? [];
594
+ ```
595
+
596
+ > 📣 Note for **TypeScript** users: `profileOptions` are typed according to the `profile`, so passing bicycle options to a car route, or setting both `departureTime` and `arrivalTime`, is caught at compile time.
597
+
598
+ <!-- Read more about directions with POST in our [official documentation](https://docs.maptiler.com/client-js/api/variables/services_routing.routing/#directionspost). -->
599
+
600
+ ##### Using GET
601
+
602
+ `directionsGet` accepts the same request as `directionsPost`, except for the fields that cannot be expressed as query parameters: the per-location `heading` and `waypoint`, and `avoidLocations`. Use `directionsPost` if you need any of them.
603
+
604
+ ```ts
605
+ const result = await maptilerClient.routing.directionsGet({
606
+ profile: "pedestrian",
607
+ profileOptions: { walkingSpeed: 4 },
608
+ locations: [
609
+ { lon: 14.4005, lat: 50.0909 }, // Prague Castle
610
+ { lon: 14.4213, lat: 50.0875 }, // Old Town Square
611
+ ],
612
+ });
613
+ ```
614
+
615
+ <!-- Read more about directions with GET in our [official documentation](https://docs.maptiler.com/client-js/api/variables/services_routing.routing/#directionsget). -->
616
+
617
+ ##### Route geometry
618
+
619
+ The geometry of each route leg is decoded by the client into an array of _GeoJSON_ positions `[lng, lat]`, so it can be used right away, for example to build a `LineString` to add to a map, or as the `path` of an [automatic static map](#automatic-static-maps):
620
+
621
+ ```ts
622
+ // Not mandatory, but it's to explain where the type comes from:
623
+ import { LineString } from "geojson";
624
+
625
+ const routeLine: LineString = {
626
+ type: "LineString",
627
+ coordinates: result.route.legs.flatMap((leg) => leg.geometry),
628
+ };
629
+
630
+ const imageLink = maptilerClient.staticMaps.automatic({
631
+ path: routeLine.coordinates,
632
+ pathStrokeColor: "blue",
633
+ });
634
+ ```
635
+
636
+ #### Request options and errors
637
+
638
+ All routing functions accept a second argument with options applying to the request itself:
639
+
640
+ - `apiKey` to use a different API key than the one in `config`
641
+ - `fetchExtras` with extra options for the underlying `fetch()` call, e.g. a `signal` to abort the request
642
+ - `adjustSearchParams`, a callback that can modify the URL search parameters before the request is sent
643
+
644
+ When the API returns an error, a `ServiceError` is thrown. Its message includes the error message from the API, and its `res` property holds the HTTP response, from which you can read the error `code` (see the `ApiErrorCode` type for the known values):
645
+
646
+ ```ts
647
+ const controller = new AbortController();
648
+
649
+ try {
650
+ const result = await maptilerClient.routing.directionsPost(request, {
651
+ fetchExtras: { signal: controller.signal },
652
+ });
653
+ } catch (error) {
654
+ if (error instanceof maptilerClient.ServiceError) {
655
+ const { code } = await error.res.json(); // e.g. "MT_PATH_NOT_FOUND"
656
+ }
657
+ }
658
+ ```
659
+
466
660
  ### 🧮 Math
467
661
 
468
- Some operations can be fairly repetitive: WGS84 to Mercator, WGS84 to *zxy* tile index, distance between two points with Haversine formula, etc. As a result, we have decided to expose a `math` package providing the most recurrent feature, so that, just like us at MapTiler, you no longer need to copy-paste the same function from your previous project!
662
+ Some operations can be fairly repetitive: WGS84 to Mercator, WGS84 to _zxy_ tile index, distance between two points with Haversine formula, etc. As a result, we have decided to expose a `math` package providing the most recurrent feature, so that, just like us at MapTiler, you no longer need to copy-paste the same function from your previous project!
469
663
 
470
664
  The `math` package differs from the others in the sense that it does not call the MapTiler Cloud API, instead it operates fully on the machine it's running on.
471
665
 
@@ -503,6 +697,8 @@ const tileXY = maptilerClient.math.wgs84ToTileIndex(montBlancPeakWgs84, 14);
503
697
  // and many more!
504
698
  ```
505
699
 
700
+ Please find out more about the math package in our [official documentation](https://docs.maptiler.com/client-js/api/variables/services_math.math/).
701
+
506
702
  <br>
507
703
 
508
704
  ## 💬 Support