I am currently developing a leaflet map to display agencies with dynamically created markers. Additionally, there is a list of agencies where clicking on each agency will automatically zoom in on the corresponding marker on the map. Now, I want to show agency information in a popup when either the agency card or the marker itself is clicked. While successfully achieving this for marker clicks, I am facing issues when implementing it for agency card clicks. To pinpoint the problem, I have outlined my approach below:
Firstly, here is my HTML code snippet for the cards:
<div class="card border border-secondary rounded" onclick="moveMap({{ agency.latitude }}, {{ agency.longitude }}, {{ agency.id }})" style="cursor: pointer; z-index: 1000">
... // rest of the html code
As my backend runs on Django, I utilize {{}}
s.
In the moveMap()
function, I pass the agency.latitude
, agency.longitude
, and agency.id
. Here's the corresponding JavaScript code:
function moveMap(lat, long, id) {
map.flyTo([lat, long], 14, {
animate: true,
duration: 3.5,
});
openPopupByID(id);
}
After moving the map to the correct marker location, the openPopupById()
function is called with the id
as a parameter. The function implementation is as follows:
function openPopupByID(agency_id) {
for (let item in markerList) {
if (item["id"] === agency_id) {
item.openPopup();
}
}
}
Here, I rely on markerList
which is initialized as shown below:
let markerList = [];
// creating markers using coorList
for (let dataSet of coorList) {
let latNumber = parseFloat(dataSet[0]);
let longNumber = parseFloat(dataSet[1]);
let marker = L.marker(L.latLng(latNumber, longNumber)).addTo(map);
// displaying agency info in popups
marker.bindPopup(setMarkerInfo(dataSet[2]));
// adding each marker to the markerList
marker["id"] = dataSet[2];
markerList.push(marker);
}
The coorList
consists of arrays containing three values: agency.latitude
, agency.longitude
, and agency.id
indexed at 0, 1, and 2 respectively.
Therefore, I have a markerList
comprising marker objects, and by assigning an id
property with marker["id"] = dataSet[2];
, I have included identification to the marker object.
However, while trying to access the id
of a marker within the openPopupByID()
function, I encounter 'undefined' output from the console. Upon logging the structure of markerList
with console.log(markerList)
, the following output is obtained:
https://i.sstatic.net/jMHeN.png
This clearly shows the presence of the id
property in the marker objects.
Hence, what could be causing the issue? And where did I go wrong?