Add 3D terrain to a map
Use setTerrain to add 3D terrain to a map using a raster terrain source.
by fxi
HTML
<script src="https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.css">
<div id="map"></div>
CSS
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
JavaScript
mapboxgl.accessToken =
"pk.eyJ1IjoiaGVsc2lua2kiLCJhIjoiY2puZW5rZ3N6MGRzYzNwb3drOW12MWEzdyJ9.IZC03hW3hKtBcbMgD0_KPw";
const s_catalina = [-118.5938, 33.4698];
const map = new mapboxgl.Map({
container: "map",
zoom: 14,
center: s_catalina,
pitch: 65,
bearing: 122,
style: "mapbox://styles/mapbox/satellite-streets-v12",
});
map.on("style.load", () => {
map.addSource("mapbox-dem", {
type: "raster-dem",
url: "mapbox://mapbox.mapbox-terrain-dem-v1",
tileSize: 512,
maxzoom: 14,
});
map.setTerrain({
source: "mapbox-dem",
exaggeration: 1.5,
});
map.addSource("points", {
type: "geojson",
data: {
type: "FeatureCollection",
features: [{
type: "Feature",
geometry: {
type: "Point",
coordinates: s_catalina,
},
properties: {
title: "hello",
},
}, ],
},
});
map.addLayer({
id: "points",
type: "circle",
source: "points",
paint: {
"circle-radius": 100,
"circle-color": "#000000",
},
});
clear();
});
function clear() {
const idSource = "points";
const idLayer = "points";
const exists = Boolean(map.getSource(idSource));
if (!exists) {
return;
}
map.removeLayer(idLayer);
map.removeSource(idSource);
}
/**
* Working version
*/
async function clearWorking() {
const idSource = "points";
const idLayer = "points";
const exists = Boolean(map.getSource(idSource));
if (!exists) {
return;
}
map.removeLayer(idLayer);
await map.once('idle');
map.removeSource(idSource);
}