Attempting to plot bus routes on a map using leaflet with geojson for coordinates. Facing issues with making the bus line bold when clicked, and reverting the style of previously clicked features back to default.
Current Progress
function $onEachFeature(feature, layer) {
layer.on({
click: function(e) {
//highlight the clicked feature
var $layer = e.target;
var highlightStyle = {
opacity: 1,
weight: 5
};
$layer.bringToFront();
$layer.setStyle(highlightStyle);
}
});
}
//leaflet map tile code would be here
//adding features with $oneachfeature function
var busFeature = L.geoJson(busRoutes, {
style: defaultBusRouteColor,
onEachFeature : $onEachFeature
});
busFeature.addTo(map);
The current implementation successfully changes the style of the clicked feature to highlightStyle
. However, the issue is that this style persists even after clicking another feature. How can I remove the previously clicked feature's style so only one remains highlighted at a time?
Attempts so far include using jQuery's addClass/removeClass, layer.resetStyle()
with leaflet, among others. Keep in mind, this needs to work smoothly on mobile devices as well; the desktop version already has a hover-based feature highlighting without any problems.
function $oneachfeature(feature, layer){
layer.on({
mouseover: function (e){makes feature bold}
});
layer.on({
mouseout: function (e){makes feature normal again}
});
}
Any suggestions?