Search code examples
javascriptjqueryhtmlleafletgeojson

Assigning ID to div from GeoJSON data


I have some GeoJSON data that are assigned to ids, like so: enter image description here

The coordinate values from this data are used to create markers in LeafletJS. I have attempted to assign the id to each marker like so:

layer.markerID = feature.properties.id;

However, I would like to assign the same id from the GeoJSON to a div that will eventually display other aspects of the data, such as "firstname" and "lastname." This way, the div id and the marker id would be linked together, depending on which marker was clicked. So if a marker with an id of 99 was clicked, then the data in the div (which would have an id of 99) would correspond to that marker. The idea is that these ids are generated dynamically

I'm just not quite sure how to go about tackling this. Any and all help would be greatly appreciated!

Edit: Just adding some additional code. Here is how I am creating the markers for my map:

$.getJSON("json.php", function(json) {
    var testlayer = L.geoJson(json, {
      style: function (feature) {
        return feature.properties.style;
      },
      onEachFeature: function (feature, layer) {
        layer.markerID = feature.properties.id;
        layer.bindPopup("<strong>ID:</strong> " + feature.properties.id + "<br>" + "<strong>Name:</strong> " + feature.properties.firstname + " " + feature.properties.lastname);
      }
    })

Solution

  • So I've finally managed to figure it out. Here's what I came up with in case anyone else ever has this issue.

    onEachFeature: function (feature, layer) {
            layer.markerID = feature.properties.id;
            layer.bindPopup("<strong>ID:</strong> " + feature.properties.id + "<br>" + "<strong>Name:</strong> " + feature.properties.firstname + " " + feature.properties.lastname + "<br>" + "<strong>Location Details:</strong>" + " "  + feature.properties.locationDetails);
            layer.on({ click: slideData });
            function slideData(e){
              document.getElementById("box1").setAttribute("id", feature.properties.id);
              document.getElementsByClassName("fullName")[0].innerHTML = feature.properties.firstname + "&nbsp;" + feature.properties.lastname;
              document.getElementById("ageNumber").innerHTML = feature.properties.age;
            }
    

    By keeping everything within the same function, I was able to access the JSON and make use of the document.getElementById and document.getElementsByClassName methods to place the text into the areas that I wanted. :)

    Also, thanks @Hinrich for your help! Your suggestions really helped me think through the problem and get to my solution.