Leaflet built-in basemap styles
This tutorial shows how to change the basemap (background map) style. Our built-in styles are designed to make it easier for you to create beautiful maps, without the need for extra coding or worrying about outdated versions. Check out the list of built-in styles.
NPM module setup
npm install --save @maptiler/leaflet-maptilersdk leaflet
import { MaptilerLayer, MapStyle } from '@maptiler/leaflet-maptilersdk';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
const key = 'YOUR_MAPTILER_API_KEY_HERE';
const map = L.map('map').setView([50, 20], 4);
const mtLayer = new MaptilerLayer({
apiKey: key,
style: MapStyle.STREETS, // optional
}).addTo(map);
document.getElementById('buttons').addEventListener('click', function (event) {
let style = MapStyle.STREETS;
// Retrieve basemap style based on button id
switch (event.target.id) {
case "streets":
style = MapStyle.STREETS;
break;
case "outdoor":
style = MapStyle.OUTDOOR;
break;
case "dark":
style = MapStyle.DATAVIZ.DARK;
break;
case "light":
style = MapStyle.DATAVIZ.LIGHT;
break;
}
mtLayer.setStyle(style);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title>Leaflet built-in basemap styles | NPM example</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div id="map"></div>
<ul id="buttons">
<li id="streets" class="button">Streets</li>
<li id="outdoor" class="button">Outdoor</li>
<li id="dark" class="button">Dark</li>
<li id="light" class="button">Light</li>
</ul>
<script type="module" src="./main.js"></script>
</body>
</html>
#map {position: absolute; top: 0; right: 0; bottom: 0; left: 0;}
#buttons {
width: 90%;
margin: 0 auto;
z-index:1000;
position:absolute;
left: 40px;
}
.button {
display: inline-block;
position: relative;
cursor: pointer;
width: 20%;
padding: 8px;
border-radius: 3px;
margin-top: 10px;
font-size: 12px;
text-align: center;
color: #fff;
background: #3174ff;
font-family: sans-serif;
font-weight: bold;
}
Replace YOUR_MAPTILER_API_KEY_HERE with your own API key. Make sure to secure the key before you publish it.