MapToolkit

FREEMIUM
By Maptoolkit.com | Updated a day ago | Mapping
Popularity

9.7 / 10

Latency

146ms

Service Level

100%

Health Check

N/A

Back to All Tutorials (2)

3D terrain in MapLibre GL JS

One of the nicer features of MapLibre is the ability to create stunning maps with 3D terrain. We are proud that we contributed this feature to MapLibre GL JS and that many companies use it for their maps.

For setup and getting started please check the โ€œGetting Started with Maptoolkit and MapLibre GL JSโ€ tutorial.

There is no preloading or plugin needed, to enable 3D terrain - a few lines of code and Terrain RGB tiles are needed to add a new dimension to your maps and bring them to the next level.

Add Terrain RGB tiles and add them to the map

To enable 3D terrain you need a Terrain RGB source and have to add it to the map.

Note: Please change the &gt in the code block to a >. Itโ€™s a limitation of this editor that the character is transfered in a code block.

map.on('load', () => {
   map.addSource("terrain", {
      "type": "raster-dem",
      "tiles": [`https://maptoolkit.p.rapidapi.com/tiles/{z}/{x}/{y}/terrainrgb.webp?rapidapi-key=${apiKey}`],
      "tileSize": 256, 
      "maxzoom": 15,
      "minzoom": 5
   });
   map.setTerrain({
      source: "terrain"
   });
});

Initialize map with pitch

To show your users that 3D is enabled, it is a good idea to initialize the map already with some pitch. maxPitch limits pitching to a certain level.

let map = new maplibregl.Map({
   container: "map",
   style: `https://static.maptoolkit.net/rapidapi/styles/terrain.json?rapidapi-key=${apiKey}`,
   center: [11.40037, 47.26816],
   zoom: 12,
   pitch: 61,
   maxPitch: 85,
});

Add map control

To give the user some buttons for navigation you might want to add controls

map.addControl(
   new maplibregl.NavigationControl({
      visualizePitch: true,
      showZoom: true,
      showCompass: true
   })
);

Full code

Check a working demo and the full source code here: https://www.maptoolkit.com/doc/tileserver/maplibre-3d-terrain/

Documentation

To learn more about using Maptoolkit with MapLibre GL JS, check out the documentation at https://www.maptoolkit.com/doc/introduction/. There, youโ€™ll find code examples, demos, and more detailed instructions for working with Maptoolkit. Please also check the MapLibre documentation at https://maplibre.org/maplibre-gl-js/docs/