Reputation: 21
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:
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
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