How to Customize the OpenStreetMap Marker Icon using JavaScript

Open Street Map provides a marker icon by default. You can change the default marker icon image and customize the icon size in OpenStreetMap. Customizing the marker icon helps to match the OpenStreetMap with the website UI. This guide will show you how to customize the OpenStreetMap marker icon using JavaScript.

The following code snippet embeds OpenStreetMap with a custom marker icon in HTML.

  • Set marker icon image (iconUrl) and size (iconSize) in L.icon() method.
  • Set marker icon options (title, icon, draggable, etc.) in the L.marker() method.
// Define latitude, longitude and zoom level
const latitude = 38.8976763;
const longitude = -77.0365298;
const zoom = 14;

// Set container element to embed map
var mymap = L.map('mapWrap');

// Customize the marker icon
let customIcon = L.icon({
    iconUrl: "https://cdn-icons-png.flaticon.com/64/1301/1301421.png",
    iconSize: [40,40]
});

let iconOptions = {
    title: "My custom icon",
    draggable: true,
    icon: customIcon
}

// Add initial marker & popup window
var mmr = L.marker([0,0], iconOptions);
mmr.bindPopup('0,0');
mmr.addTo(mymap);

// Add copyright attribution
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {
    foo: 'bar',
    attribution:'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'}
).addTo(mymap);

// Set lat lng position and zoom level of map 
mmr.setLatLng(L.latLng(latitude, longitude));
mymap.setView([latitude, longitude], zoom);

// Set marker onclick event
mmr.on('click', openPopupWindow);

// Marker click event handler
function openPopupWindow(e) {
    mmr.setPopupContent('Latitude: '+e.latlng.lat+' <br /> Longitude: '+e.latlng.lng).openPopup();
}

Embed OpenStreetMap with Marker in HTML using JavaScript

Leave a reply

keyboard_double_arrow_up