Leaflet - marker with id

by Alex Azuero

HTML

<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css">
<div id="map"></div>

CSS

#map { 
    height: 400px; 
}

JavaScript

// Create the map
var map = L.map('map').setView([39.5, -0.5], 5);

// Set up the OSM layer
L.tileLayer(
    'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', 
    {maxZoom: 18}).addTo(map);

// Custom id for the marker
var id = "13452"

//Handle marker click
var onMarkerClick = function(e){
    console.log(this);
    alert("You clicked on marker with customId: " +this.options.myCustomId);   
}

//Create new marker
var marker = L.marker([36.83711,-2.464459], {myCustomId: id});
//Show popup when clicking on marker
marker.bindPopup('My marker with customId: ' +id);
//Handle click on marker
marker.on('click', onMarkerClick);
//Add marker to map
marker.addTo(map);