I have an array containing points objects from which I plot my markers.
var Allpoints=[{
"names":"first", "eastings":556568, "northings":446445, "description": "aijaskj jnrkajra skjanjanek ", "elevations": 5668, "LatLong": [10.769869, -2.337035]
},
{
"names":"first", "eastings":556568, "northings":446445, "description": "aijaskj jnrkajra skjanjanek ", "elevations": 5668, "LatLong":[10.387760, -0.448079]
},
{
"names":"first", "eastings":556568, "northings":446445, "description": "aijaskj jnrkajra skjanjanek ", "elevations": 5668, "LatLong":[9.104698, -0.882039]
},
{
"names":"first", "eastings":556568, "northings":446445, "description": "aijaskj jnrkajra skjanjanek ", "elevations": 5668, "LatLong":[5.580339, -2.266316]
},
{
"names":"first", "eastings":556568, "northings":446445, "description": "aijaskj jnrkajra skjanjanek ", "elevations": 5668, "LatLong":[8.050960, -1.247334]
},
{
"names":"first", "eastings":556568, "northings":446445, "description": "aijaskj jnrkajra skjanjanek ", "elevations": 5668, "LatLong":[5.142810, -1.961445]
},
{
"names":"first", "eastings":556568, "northings":446445, "description": "aijaskj jnrkajra skjanjanek ", "elevations": 5668, "LatLong":[6.115865, 0.082012]
},
];
A picture of the plotted markers
I plot all the points from the array, // //automatically plot all previous markers
for (obj in Allpoints){
_newMarker = L.marker(Allpoints[obj].LatLong,
{title: Allpoints[obj].names,
riseOnHover: true,
},
).addTo(mymap);
allMarkers.push(_newMarker);
// not working i.e. THIS IS THE PROBLEM
_newMarker.addEventListener('click', markerDetails(_newMarker))
}
and then I want to add an event listener to all makers so that when it is clicked, a function will take the details of that current point and display it in an HTML pane I created.
function markerDetails(currentMarker){
$("#returnControlName").html(currentMarker.controlName);
$("#returnControlEastings").html(controlEastings);
$("#returnControlNorthings").html(controlNorthings);
}
the problem is, I cannot seem to add an event listener that will listen to each of them and retrieve the data of that marker and display it on the pane. Any help on how to go about this issue will be relieving.
The problem is, that when you add in a listener a function and add to the function ()
it is executed diretly and not when the listener is executed.
So correct would be: _newMarker.addEventListener('click', markerDetails)
Change your code to:
for (obj in Allpoints){
_newMarker = L.marker(Allpoints[obj].LatLong,
{title: Allpoints[obj].names,
riseOnHover: true,
},
).addTo(mymap);
_newMarker.data = Allpoints[obj]; // save the objectData on the marker
allMarkers.push(_newMarker);
_newMarker.on('click', markerDetails);
}
function markerDetails(e){
var currentMarker = e.target;
var obj = currentMarker.data; //your objectData
$("#returnControlName").html(currentMarker.controlName);
$("#returnControlEastings").html(controlEastings);
$("#returnControlNorthings").html(controlNorthings);
}