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'

    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'

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 Jan 18, 2017 at 13:46

1 Answer 1


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

var rlayer = null;


  function() {

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

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

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.