Add custom marker to a Leaflet map
Leaflet map library allows creating markers of different types and forms.
In this code sample, we would like to show how you can use icons generated by Geoapify Marker Icon API as Leaflet markers. The full version of the code sample you can find on JSFiddle.
1. Generate an icon and get the icon URL
Design a map marker icon with the Marker Icon API playground. You will require an API key to use the icon in your project. Register for Free, no credit card required.
2. Create a marker with the icon
size=60 sets the height of the pin; the default shadow adds 7 px below it, so the image is 46 × 67 px. scaleFactor=2 returns the PNG at double resolution (92 × 134 px) for sharp markers on retina screens, displayed at 46 × 67 px. The anchor sits at the tip of the pin, above the shadow. See How to Add Markers to a Map for placement and anchors in other map libraries.
const markerIcon = L.icon({
iconUrl: `https://api.geoapify.com/v2/icon?type=awesome&color=%233e9cfe&size=60&icon=paw&contentSize=29&noWhiteCircle&scaleFactor=2&apiKey=${myAPIKey}`,
iconSize: [46, 67], // displayed size of the icon, including the shadow
iconAnchor: [23, 60], // point of the icon which will correspond to marker's location
popupAnchor: [0, -62] // point from which the popup should open relative to the iconAnchor
});
const zooMarker = L.marker([48.096980, 11.555466], {
icon: markerIcon
}).addTo(map);
3. Add a popup to the marker
Here is an example of a simple text popup:
const zooMarkerPopup = L.popup().setContent("This is Munich Zoo");
const zooMarker = L.marker([48.096980, 11.555466], {
icon: markerIcon
}).bindPopup(zooMarkerPopup).addTo(map);
The Leaflet library lets you generate more complicated popups based on an HTML element provided to the setContent() function.