I am building an ionic3 app and using leaflet for the map functions. However i encountered a strange behavior. After page load the location is automaticly fetched if GPS is turned on. After this for a more precise location the given marker can be moved. After this if i click on the "Locate me" button then the marker is removed but after the location if fetched again i get two markers added to my current location. Its like the marker got removed from the map but not from the markers array. Every time i click "Locate me" i get an extra marker so after the second click i have 3 markers in total and on.
The "Locate me" button calls the locate() function.
Here is the code that i am using:
presentAlert() {
let alert = this.alertCtrl.create({
title: 'GPS hiba',
subTitle: 'Kérem kapcsolja be a GPS vevőt a helyzete meghatározásához!',
buttons: [
{
text: 'Ok',
role: 'cancel',
handler: () => {
}
}
]
});
alert.present();
}
ionViewDidLoad() {
this.getMap();
}
getMap() {
this.map = leaflet.map("map");
leaflet.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attributions: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
minZoom: 6
}).addTo(this.map);
this.map.bounds = [];
this.map.fitBounds([
[45.636684, 16.030223],
[48.708459, 22.863228]
]);
this.map.setMaxBounds([
[45.636684, 16.030223],
[48.708459, 22.863228]
]);
this.locate();
}
locate() {
this.map.locate({
setView: true,
maxZoom: 10,
enableHighAccuracy: true
});
let marker;
this.map.on('locationfound', (e) => {
if (marker && this.map.hasLayer(marker)) {
this.map.removeLayer(marker);
}
let lat = e.latitude;
let lng = e.longitude;
marker = new leaflet.marker([e.latitude, e.longitude], {draggable: 'true'});
marker.on('dragend', function (event) {
marker = event.target;
let position = marker.getLatLng();
lat = position.lat;
lng = position.lng;
marker.setLatLng(new leaflet.LatLng(position.lat, position.lng), {draggable: 'true'});
});
this.map.addLayer(marker);
});
this.map.on('locationerror', (err) => {
this.presentAlert();
})
}
Every help will be much appreaciated. Regards, Trix