Monday 17 July 2017

jquery - Hide/Show route layer in Leaflet when click on button (Easy Button plugin)


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: '© Map Data OpenStreetMap 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



Answer



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);



No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...