Reputation: 21
I want to swap between layers in leaflet dynamically. So i think hide layers. Here is my code
<div id="map"></div>
<div>
<button onclick='fun1()'>yellowhide</button>
<button onclick='fun2()'>redhide</button>
</div>
<script>
//same lat long means overlapping
addressPoints1= [ [-37.8210922667, 175.2209316333, "2"], [-37.8210819833, 175.2213903167, "3"], [-37.8210881833, 175.2215004833, "3"], [-37.8211946833, 175.2213655333, "1"]] addressPoints2= [ [-37.8210922667, 175.2209316333, "2"], [-37.8210819833, 175.2213903167, "3"], [-37.8210881833, 175.2215004833, "3"], [-37.8211946833, 175.2213655333, "1"]]
var tiles=L.tileLayer('http://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', { attribution: '', id: 'examples.map-20v6611k' }) var map = L.map('map', { center: [-37.87, 175.475], zoom: 16, layers: [tiles] }); var heat1 = L.heatLayer(addressPoints1,{ gradient: {1:"red"} }).addTo(map); var heat2 = L.heatLayer(addressPoints2,{ gradient: {1:"yellow"} }).addTo(map);
function fun1(){ console.log("hide yellow layer");
$('.heat2').hide(); } function fun2(){ console.log("hide red layer");
$('.heat1').hide();
}
but it's not working.
Upvotes: 2
Views: 3425
Reputation: 123
if you haven't find a solution for this, have a look into the Leaflet Layer Controls.
With the controls, you can change the visible layers of a map.
var baseLayers = {
"Mapbox": tiles
};
var overlays = {
"Fancy Heatmap": heat1,
"Another fancy Heatmap": heat2
};
L.control.layers(baseLayers, overlays).addTo(map);
HTH,
Meykel
Upvotes: 0
Reputation: 28638
There is no need to use jQuery and query for those layers because you've already declared before as variables heat1
and heat2
. You can use those to remove them from the map or add them again. At the moment you're using the addTo
method of the layer to add the layer to the map:
var heat1 = L.heatLayer().addTo(map);
Which in the background executes the addLayer
method of the map instance:
map.addLayer(heat1);
The map instance also has removeLayer
method for removing layers from the map:
map.removeLayer(heat1);
So you can use that in your onclick handler:
function fun1 () {
map.removeLayer(heat1);
}
Here's the reference with all the layer methods of L.Map: http://leafletjs.com/reference.html#map-stuff-methods
Upvotes: 2