3

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

sleepy_daze
  • 521
  • 2
  • 7
  • 24
  • Do you have a website you can point to in order to give a better understanding? im a novice with java script and leaflet however ive been working with it this week doing the exact same as you i think.. but if you can provide some more info or examples i will know exactly what you mean. also please see here: https://www.google.co.uk/?gws_rd=ssl#q=leaflet.js+github+examples There all pre-coded examples on github.. it helped me a great deal. – Birdy Jul 30 '15 at 20:07
  • @Birdy, I don't have a website up yet (I'm working locally), but I can show you some of my code! I just edited my question. – sleepy_daze Aug 02 '15 at 17:20

1 Answers1

7

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

gusjap
  • 2,397
  • 5
  • 24
  • 38