How do should I hide the Leaflet Routing Machine route and markers on mouseout event?
Currently, I have regular Leaflet marker, that has mouseover/mouseout events. When mouseover event is fired and route belonging to that marker is created using L.Routing.control
route = L.Routing.control({
show: false,
addWaypoints: false,
draggableWaypoints: false,
fitSelectedRoutes: false,
waypoints: [
L.latLng(locations.aLat, locations.aLng), // Hardcoded coordinates
L.latLng(locations.bLat, locations.bLng), // Hardcoded coordinates
],
});
route.addTo(map);
When mouseout event is triggered I call route.remove()
which deletes the route completely.
The problem with this approach:
I have tried to set route opacity to 0 and marker icon size to 0 on mouseout event, however, you cannot dynamically change styles in Leaflet Routing Machine.
Another approach I took was to give css class names to routes and try to set display: none
but assigning classes to many different routes is a really messy way to solve this.
The demo is quite neat if you want to play around.(Updated works as supposed to) Grab it here
The solution is to create the route once and save it somewhere for later use. In my case, it is saved on marker.options
marker = L.marker(pointA, {
options: {
route: createRoute(pointA, pointB), // Function that return route object(L.Routing.control)
},
})
After you have the route created you can:
if (marker.options.options.route._map) { Do something }
marker.options.options.route.addTo(map);
marker.options.options.route.remove();
You can find a working demo here