Add custom icons with markers
Enhance your map by incorporating personalized icons using the Marker feature. This functionality allows you to include custom icons that align with your specific preferences.
NPM module setup
npm install --save @maptiler/sdk
import { Map, MapStyle, config } from '@maptiler/sdk';
import '@maptiler/sdk/dist/maptiler-sdk.css';
config.apiKey = 'YOUR_MAPTILER_API_KEY_HERE';
const geojson = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'properties': {
'message': 'Foo',
'iconSize': [60, 60]
},
'geometry': {
'type': 'Point',
'coordinates': [-66.324462890625, -16.024695711685304]
}
},
{
'type': 'Feature',
'properties': {
'message': 'Bar',
'iconSize': [50, 50]
},
'geometry': {
'type': 'Point',
'coordinates': [-61.2158203125, -15.97189158092897]
}
},
{
'type': 'Feature',
'properties': {
'message': 'Baz',
'iconSize': [40, 40]
},
'geometry': {
'type': 'Point',
'coordinates': [-63.29223632812499, -18.28151823530889]
}
}
]
};
const map = new Map({
container: 'map',
style: MapStyle.STREETS,
center: [-65.017, -16.457],
zoom: 5
});
// add markers to map
geojson.features.forEach(function (marker) {
// create a DOM element for the marker
const el = document.createElement('div');
el.className = 'marker';
el.style.backgroundImage =
`url(https://docs.maptiler.com/sdk-js/examples/custom-marker-icons/${marker.properties.iconSize[0]}.jpg)`;
el.style.width = marker.properties.iconSize[0] + 'px';
el.style.height = marker.properties.iconSize[1] + 'px';
el.addEventListener('click', function () {
window.alert(marker.properties.message);
});
// add marker to map
new maptilersdk.Marker({element: el})
.setLngLat(marker.geometry.coordinates)
.addTo(map);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title>Add custom icons with markers | NPM example</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<style>
.marker {
display: block;
border: none;
border-radius: 50%;
cursor: pointer;
padding: 0;
}
</style>
<div id="map"></div>
<script type="module" src="./main.js"></script>
</body>
</html>
body {margin: 0; padding: 0;}
#map {position: absolute; top: 0; bottom: 0; width: 100%;}