Reputation: 83
I am developing a website that has a mapping and i am using leaflet. Now im on the part that i will hide /show markers that i made.
below is my code finding the image that i want and use it as a marker
var Icon1 = L.icon({
iconUrl: 'legends/fire.GIF',
iconSize: [170, 120], // size of the icon
iconAnchor: [100, 120], // point of the icon which will correspond to marker's location
popupAnchor: [-7, -80] // point from which the popup should open relative to the iconAnchor
the other one below is my code when putting the mark on the map.
function mark()
{
if (select1.value === "Fire"){
var note = document.getElementById('note');
var datepick = document.getElementById('demo1');
var timepick = document.getElementById('timepick');
map.on('click', function(e){
var marker = new L.Marker(e.latlng,{icon: Icon1});
marker.bindPopup("</a><br><strong>FIRE</strong></br><strong>Date:</strong>"+datepick.value+"</br><strong>Time:</strong>"+timepick.value+"</br><strong>Address:</strong>"+note.value+"<strong><br><strong>Suspect Sketch</strong><br><a href=legends/suspect.jpg rel=lightbox><img src = legends/suspect.jpg height=100 width = 100/>").addTo(map);
marker.on('dragend');
});
This is my code in hiding the marker.
script type="text/javascript">
function closure(marker){
var checkbox = document.getElementById("chbx")
$(chbx).click(function(){
if(map.hasLayer(marker)){
window.alert("I want to hide the marker");
}
window.alert("I want to show the marker");
})
}
</script>
This is just what i wanted. 1.Add A marker on the map 2.Hide/Show the marker in the map 3.Make this happen during run time or when i try it.
I try everything but still nothing happens. What is the right thing to do to call my hide/show function in checkbox?
Upvotes: 5
Views: 13402
Reputation: 111
In some cases for hiding markers we may use such method, may be.
marker._icon.style.display = 'none';
if (value._popup._isOpen)
{
marker.closePopup();
}
For show markers after hiding.
marker._icon.style.display = '';
Upvotes: 1
Reputation: 1912
Here's a way to do it: Define a function which takes marker as its argument, and with jQuery create a function to toggle the visibility of the layer:
function closure(marker){
$('#yourcheckbox id').click(function(){
if(map.hasLayer(marker)){
map.removeLayer(marker)
}
else {map.addLayer(marker)}
})
}
Than, inside the click event of the map, add the closure function:
map.on('click', function(e){
marker = new L.Marker(e.latlng).addTo(map);
closure (marker)
})
Upvotes: 8
Reputation: 1571
With .addTo(map)
should works.
However, you can use addLayer
and removeLayer
for add/remove markers:
var marker = new L.Marker(e.latlng,{icon: Icon1});
marker.bindPopup('<div>Hello World</div>');
//add the marker to the map
map.addLayer(marker);
//remove the marker from the map
map.removeLayer(marker);
I assume that you have created the map
Upvotes: 0