Extract Attributes For Markers In Leaflet, Onclick Event
I'm using a JSON file to plot the markers in Leaflet: [{ 'id': 1, 'date': '1/1/2015', 'Title': 'Trinity College', 'Latitude': 41.745167, 'Longitude': -72.69263}, { 'id': 2,
Solution 1:
Since you already create a Popup for each Marker, you could already embed your JSON data into its content.
But if for whatever reason you cannot do it, you just have to reference your JSON data from your created Leaflet Markers, as described in:
Leaflet: Including metadata with CircleMarkers
Within your loop, use any of the 3 described methods to attach your jsonDataObject[i]
to your marker
.
Then in your "click"
handler, your clicked Marker is accessible as e.target
, then depending on how you attached your JSON data, you can retrieve it with e.target.myJsonData
, e.target.options.myJsonData
or e.target.getProps().myJsonData
.
For example:
var jsonDataObject = [{
"id": 1,
"date": "1/1/2015",
"Title": "Trinity College",
"Latitude": 41.745167,
"Longitude": -72.69263
},
{
"id": 2,
"date": "1/2/2015",
"Title": "Wesleyan University",
"Latitude": 41.55709,
"Longitude": -72.65691
}
];
var map = L.map('map').setView([41.65, -72.67], 9);
for (var i = 0; i < jsonDataObject.length; i++) {
var marker = L.marker(L.latLng(parseFloat(jsonDataObject[i].Latitude), parseFloat(jsonDataObject[i].Longitude)));
marker.bindPopup(jsonDataObject[i].Title, {
autoClose: false
});
map.addLayer(marker);
marker.on('click', onClick_Marker)
// Attach the corresponding JSON data to your marker:
marker.myJsonData = jsonDataObject[i];
}
functiononClick_Marker(e) {
var marker = e.target;
popup = L.popup()
.setLatLng(marker.getLatLng())
.setContent("The number id is: " + marker.myJsonData.id)
.openOn(map);
}
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
<linkhref="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css"integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ=="crossorigin="" /><scriptsrc="https://unpkg.com/leaflet@1.3.1/dist/leaflet-src.js"integrity="sha512-IkGU/uDhB9u9F8k+2OsA6XXoowIhOuQL1NTgNZHY1nkURnqEGlDZq3GsfmdJdKFe1k1zOc6YU2K7qY+hF9AodA=="crossorigin=""></script><divid="map"style="height: 180px"></div>
Post a Comment for "Extract Attributes For Markers In Leaflet, Onclick Event"