How to make a map with pins using Leaflet
This example shows how to make a map with pins using Leaflet JS. Load a geoJSON of points in Leaflet JS and add your custom pins or icons.
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([45.9767521, 7.6569418], 12);
const mtLayer = new MaptilerLayer({
apiKey: key,
style: MapStyle.BASE, // optional
}).addTo(map);
const leafIcon = new L.icon({
iconUrl: "https://docs.maptiler.com/sdk-js/examples/custom-points-icon-png/underground.png", //your custom pin
iconSize: [24, 26],
});
async function loadGeoJSON() {
const response = await fetch(`https://api.maptiler.com/data/YOUR_MAPTILER_DATASET_ID_HERE/features.json?key=${key}`);
const geoJSON = await response.json();
L.geoJSON(geoJSON, {
pointToLayer: function (geoJsonPoint, latlng) {
return L.marker(latlng, {icon: leafIcon});
}
}).addTo(map);
}
loadGeoJSON();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title>How to make a map with pins using Leaflet | NPM example</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div id="map"></div>
<script type="module" src="./main.js"></script>
</body>
</html>
#map {position: absolute; top: 0; right: 0; bottom: 0; left: 0;}
Replace YOUR_MAPTILER_API_KEY_HERE with your own API key. Make sure to secure the key before you publish it.
Learn more
Check out the Leaflet marker with a custom icon to learn How to customize Leaflet icons.