In this tutorial, you'll learn how to build a 3D map using MapLibre GL JS v2. We will show you how to make a simple map application allowing you to zoom and pan MapTiler maps in 3D using MapLibre. By the end, you will have a map that looks like this in a fully interactive web interface:
Minimal requirements for completing this tutorial.
In this step, we will learn how to create a Simple Map with MapLibre GL JS.
Create a file called
index.html and write the following lines:
<div> tag into your page. This div will be the container to display the map. Write the following line into the body of the page.
Initialize the map
<head> of your HTML file. Add these lines in the
To create a fullscreen map, add the following style in the
<head> of your page.
<body>, write the following code to visualize and add the map to our HTML page.
Open the index.html file in your browser, and you will see a full-screen map, like the one shown in the map below.
Add 3D terrain to a map
Next, we will see how to create a 3D terrain map. To make our 3D map, we will use the elevation data from MapTiler Terrain RGB
To create the 3D map, we must add a new layer. To do this, we must wait until the map resources have been loaded, including the style. Only after this can we add our layers to the map. The
load event is fired immediately after all necessary resources have been downloaded and the first visually complete rendering of the map has occurred. Add these lines after the map initialization.
When adding a new layer, the first thing we have to do is define the layer's data source. Inside the
load event callback function, write the followings lines.
The valid types for the encoding option are: "mapbox", "mtk" and "terrarium".
To add the terrain layer, we use the
setTerrain method that receives the id of the data source as a parameter. Add the following line just after where we have added the data source.
Finally, to see the effect of the 3D of the map, we will give some tilt to the map's initial view. Add the following line to the maps options.
script should look like this.
Refresh the page in your browser and see a 3D map like this one.
Congratulations! You have finished your fullscreen 3D map app using MapLibre GL JS. You can explore more about MapLibre GL JS for your map in the MapLibre API reference.