[GIS] leaflet – change routing vehicle when clicked on button

javascriptleafletrouting

I want to change the routing vehicle when clicked on a button. The default routing vehicle is "car" ("auto") when clicked a button routing vehicle should change to "foot" ("pedestrian").

I am using leaflet.easy.button and leaflet.routing.machine plugins, as routeservice I use mapzen.

Links:

My code:

  1. Routing.control :

    var myRouter = L.Routing.control({
        router: L.Routing.mapzen('valhalla-ABCDEFG', {
            costing:"auto"}),
        routeWhileDragging: true,
        geocoder: L.Control.Geocoder.nominatim(),
        formatter: new L.Routing.mapzenFormatter()
    }).addTo(map);
    
  2. Easy.Button :

    L.easyButton('<img src="pic.png">', function(btn,map){
        myRouter.route({costing: "pedestrian"});
    }).addTo(map);
    

Any ideas what could be wrong? Or maybe a different way to approach this problem.

Best Answer

The route method does not pass any options on to the router. You'll want to use the getRouter method to set the router options first. Then you can recalculate using route:

L.easyButton('<img src="pic.png">', function(btn,map){
  myRouter.getRouter().options.costing = "pedestrian";
  myRouter.route();
}).addTo(map);