user3398945
user3398945

Reputation: 93

How to remove L.Routing.line in leaflet with Leaflet Routing Machine?

I am trying to get a function to work that updates a L.Routing.line with Leaflet Routing Machine whenever a user adds or deletes a waypoint.

My code to date (slight adaptation from http://www.liedman.net/leaflet-routing-machine/interaction.html):

function routeImplement(){
    if (routewpts.length >= 2) {
        router.route(routewpts, function(err, routes) {
            if (routeline) {
                map.removeLayer(routeline);
            };

            if (err) {
                alert(err);
            } else {
                routeline = L.Routing.line(routes[0]).addTo(map);
            };
        });
    }
    else{
        if (routeline) {
           map.removeLayer(routeline);
        };
    };
}

routewpts is an array of latLngs, routeline is supposed to be the L.Routing.line, router=L.Routing.osrm();, and map is the leaflet map (all globals). The function works fine for creating a line.

The issue that I am having is that the map.removeLayer(routeline); doesn't seem to work. There are two issues it seems: one is that L.Routing.line doesn't seem to return anything, so routeline is remaining undefined. Second, if I dispense with the use of a handle, and try to use map.removeLayer directly on L.Routing.line, I get some crazy error about a bad request to OSRM.org.

Thanks for any suggestions.

Upvotes: 2

Views: 5193

Answers (2)

Denis Kkk
Denis Kkk

Reputation: 61

the first thing that i mooved forward is to use arrow function

function routeImplement(){
    if (routewpts.length >= 2) {
        router.route(routewpts, (err, routes) => { //arrow function
            if (routeline) {
                map.removeLayer(routeline);
            };

            if (err) {
                alert(err);
            } else {
                routeline = L.Routing.line(routes[0]).addTo(map);
            };
        });
    }
    else{
        if (routeline) {
           map.removeLayer(routeline); // but still this line doesnt work for me
        };
    };
}

Upvotes: 1

user3398945
user3398945

Reputation: 93

Well... It turns out the way to get this to work is to break up the L.Routing.line call:

routeline = L.Routing.line(routes[0]);
routeline.addTo(map);

With that the routeline handle works and everything else functions fine. I don't understand Leaflet (or the Routing Machine) well enough to explain why it gave up on returning anything if the line is immediately added to the map.

Upvotes: 0

Related Questions