blackscholes
blackscholes

Reputation: 21

Getting a different geoJSON file based on each features' property ID

I'm new to javascript - but I've written the following code to plot the location of trains, and add the train route (see screenshot) for each feature using leaflet's "onEachFeature":

//Add marker description before being added to layer
function eachFeature(feature, layer) {
    layer.bindPopup(feature.properties.id);
    layer.on({
        mousedown: onClick,
        mouseover: whenHovered,
        mouseout: offHovered
    });
}

// Show/hide train lines on hover
function onClick() {
  $.getJSON("AEHL_2b.geojson", 
    function(data) { 
      staticRoute = L.geoJson(data);
      staticRoute.addTo(map); 
  });
}

function whenHovered() {
  $.getJSON("OPS_1b.geojson", 
    function(data) { 
      hoverRoute = L.geoJson(data);
      hoverRoute.addTo(map); 
  });
}

function offHovered() {
  map.removeLayer(hoverRoute);
}

Basically, I'm using the onEachFeature function of leaflet (specifically leaflet-realtime) to try do two things:

  1. Add a popup with the feature's leaflet ID
  2. Download a geoJson file to plot the train route based on the feature's leaflet ID.

At the moment, I've hard-coded the geoJson but I can't seem to find a way of grabbing each feature's leaflet ID to use in my getJson function.

Is it possible to grab different geoJson files and if so, could somebody please help me out with some pointers? Any help appreciated since I'm new to javascript

Thanks!

Upvotes: 0

Views: 311

Answers (1)

blackscholes
blackscholes

Reputation: 21

Self update for future self / future others - it works if you put the onClick/whenHovered/offHovered functions within the function that the onEachFeature uses. E.g.

        function eachFeature(feature, layer) {
            layer.bindPopup(feature.properties.id);
            layer.on({
                mousedown: onClick,
            });

            //Add train route when clicked, or when hovering
            function onClick(){
                $.getJSON(feature.properties.id+".geojson", 
                    function(data) { 
                      staticRoute = L.geoJson(data);
                      staticRoute.addTo(map); 
                });
            }
        }

Upvotes: 2

Related Questions