Uniquely identifying Leaflet Markers

南楼画角 提交于 2020-06-15 07:38:32

问题


I've done some research on this topic before, but I have yet to find an answer to my particular question. I am currently working with Leaflet.js. Each marker has popup text that is pulled from a MySQL database. However, some of this data does not display in the popup and is only associated with the marker.

What I would like to do is whenever a particular marker is clicked, data that is associated with it is echoed in a location other than in the popup (ie. in a DIV).

Is there a way to uniquely identify a marker so that you can pull data that is associated with it and echo it elsewhere?

Edit: Here's some code to make things a bit clearer:

Here is some of my JS:

var json_data = <?php echo json_encode($data); ?>;

for (var i = 0; i < json_data.length; i++) {
    L.marker([json_data[i].latitude, json_data[i].longitude])
    .bindPopup(json_data[i].firstName + ' ' + json_data[i].lastName + '<br>' + '<strong>Date:</strong>' + ' ' + json_data[i].dateOccurred)
    .addTo(map);
  }

And here is my PHP:

$query = "SELECT * FROM incident, victim WHERE incident.incidentID = victim.incidentID";
//converting the data from mySQL to PHP

$data = array(); //setting up an emtpy PHP array for the data to go into

if($result = mysqli_query($db,$query)) {
  while ($row = mysqli_fetch_assoc($result))
  {
    $data[] = $row;
  }
}
?>

Basically I pull the data via PHP and then encode it into JSON.

Also, thank you for your help, guys!! :)


回答1:


You can try adding a custom attribute to the marker and then get that attribute in the onClick event:

//Handle marker click
var onMarkerClick = function(e){
    alert("You clicked on marker with customId: " +this.options.myCustomId);   
}
//Create marker with custom attribute
var marker = L.marker([36.83711,-2.464459], {myCustomId: "abc123"});
marker.on('click', onMarkerClick);

Example on JSFiddle



来源:https://stackoverflow.com/questions/31732215/uniquely-identifying-leaflet-markers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!