Reputation: 228
I have a code here that displays a marker on the map based on my php.
/* Generate the map and center it in philipines on start up */
var map = L.map('map').setView([12.8797, 121.7740], 6);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
/* Mapping Variables */
var markers = new L.layerGroup();
/* On button click put a marker on the phillipine map base on condition */
$("#btn-generate").click(function(){
/* Other variables */
var d1 = $('#startdate').val();
var d2 = $('#enddate').val();
var fspcode = $('#fspcode').find(":selected").text();
$.ajax({
type: 'POST',
url: '../../php/pages/sfa/qry_map.php',
data: {
'startdate' : d1,
'enddate' : d2,
'fspcode' : fspcode
},
success: function(data) {
var data = JSON.parse(data);
data = data.aaData;
if (data.length == 0) {
sfaMsgbox("Unable to Track. No record found.");
} else {
/* Get the lat and long */
for (var i = 0; i < data.length; i++) {
var lat = data[i].lat;
var long = data[i].long;
var code = data[i].code;
var vdate = data[i].vdate;
var type = data[i].type;
var name = data[i].name;
var address = data[i].address;
var wholeinfo = "<b>FSP Assigned : </b>" + code + "<br>" +
"<b>Visit Date : </b>" + vdate + "<br>" +
"<b>Customer : </b>" + name + "<br>" +
"<b>Address : </b>" + address + "<br>" +
"<b>Type : </b>" + type;
/* Proceed in creating the map */
var marker = L.marker([lat,long]);
marker.bindPopup(wholeinfo, {
showOnMouseOver: true
});
markers.addLayer(marker);
}
}
}
});
/* Add the markers */
map.addLayer(markers);
});
And this is how I delete it.
$("#removemarker").click(function(){
/* Remove any existing Markers */
map.removeLayer(markers);
});
These codes are working however If I delete all the markers, they do delete but if I generate a new one the old marker shows again. How can I fix it?
My target here is to add and add markers no matter how many it then deletes all of it. the only problem is that the old marker displays again. TYSM
Upvotes: 2
Views: 3480
Reputation: 434
The removeLayer
function only removes the layer (basically hides it) from your map. The markers will still remain on the layerGroup
. If you want to remove all markers from the layer you probably want to use
markers.clearLayers();
instead. This will remove all current markers from the layer.
Upvotes: 3