Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uniquely identifying Leaflet Markers

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!! :)

like image 990
sleepy_daze Avatar asked Jan 20 '26 16:01

sleepy_daze


1 Answers

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

like image 71
gusjap Avatar answered Jan 23 '26 05:01

gusjap



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!