2

I have a Leaflet map with button (Easy Button plugin https://github.com/CliffCloud/Leaflet.EasyButton). When click on button on map added route layer (plugin https://github.com/perliedman/leaflet-routing-machine). Please, help me add event for button to show/hide layer when I click on button. Map example:

var map = L.map('map', {
    center: [50.0669, 35.1638],
    zoom: 15
});

L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 18,
    attribution: '&copy; Map Data <a href="https://openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);


L.easyButton('fa-level-up',
    function() {

        var routing = L.Routing.control({
            plan: L.Routing.plan([
                L.latLng(50.07132, 35.14103),
                L.latLng(50.05459, 35.18239)
            ], {
                waypointIcon: function(i) {
                    return new L.Icon.Label.Default({
                        labelText: String.fromCharCode(65 + i)
                    });
                },
                geocoder: L.Control.Geocoder.nominatim()
            }),
            routeWhileDragging: true,
            routeDragTimeout: 250
        });

var rlayer = L.layerGroup([routing]);
map.hasLayer(rlayer) ? map.removeLayer(rlayer) : map.addLayer(rlayer);      

},
    'Display Route'
).addTo(map);

I try use map.hasLayer(rlayer) ? map.removeLayer(rlayer) : map.addLayer(rlayer); but route layer after second click don't hide

  • I tried to put it on my map but when I click on the button, the console tells me 2 errors : - Uncaught TypeError: Cannot read property 'call' of undefined - Uncaught TypeError: Cannot read property 'appendChild' of undefined – Rémy Blancke Jan 18 '17 at 13:46
3

You should declare the variable rlayer outside of the easybutton function. Try that:

var rlayer = null;

L.easyButton('fa-level-up',

  function() {

    if (rlayer) {
      map.removeLayer(rlayer);
      rlayer = null;
    } else {
      var routing = L.Routing.control(...);
      rlayer = L.layerGroup([routing]);
      map.addLayer(rlayer);
    }

  }, 'Display Route').addTo(map);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.