I have Zip codes drop down list and I want to display selected zip code on leaflet map. For that I did Geo coding to get lat long. Now I want when user selects another Zip code from drop down list, previous marker should removed automatically. Please suggest me.
$.ajax({
url : "http://maps.googleapis.com/maps/api/geocode/json?address=santa+cruz&components=postal_code:"+$scope.code+"&sensor=false",
method: "POST",
success:function(data){
latitude = data.results[0].geometry.location.lat;
longitude= data.results[0].geometry.location.lng;
console.log('Your latitude is :'+latitude+' and longitude is '+longitude);
var latlng = new google.maps.LatLng(latitude, longitude);
leafletData.getMap('lfdt').then(function(map){
var marker= L.marker([latitude,longitude]).addTo(map);
var group = new L.featureGroup([marker]);
console.log("Group",group);
map.fitBounds(group.getBounds());
map.setZoom(6);
var geocoder = geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
if (results[1])
{
marker.bindPopup(results[1].formatted_address);
marker.on('mouseover', function (e) {
this.openPopup();
});
marker.on('mouseout', function (e) {
this.closePopup();
});
}
console.log("Location: " , results[1].formatted_address);
}
});
console.log("geocode",geocoder);
});
}
});
});
You can try below code
var marker;
$.ajax({
url : "http://maps.googleapis.com/maps/api/geocode/json?address=santa+cruz&components=postal_code:"+$scope.code+"&sensor=false",
method: "POST",
success:function(data){
latitude = data.results[0].geometry.location.lat;
longitude= data.results[0].geometry.location.lng;
console.log('Your latitude is :'+latitude+' and longitude is '+longitude);
var latlng = new google.maps.LatLng(latitude, longitude);
leafletData.getMap('lfdt').then(function(map){
if (marker) { // check
map.removeLayer(marker); // remove
}
marker= L.marker([latitude,longitude]).addTo(map);
var group = new L.featureGroup([marker]);
console.log("Group",group);
map.fitBounds(group.getBounds());
map.setZoom(6);
var geocoder = geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
if (results[1])
{
marker.bindPopup(results[1].formatted_address);
marker.on('mouseover', function (e) {
this.openPopup();
});
marker.on('mouseout', function (e) {
this.closePopup();
});
}
console.log("Location: " , results[1].formatted_address);
}
});
console.log("geocode",geocoder);
});
}
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.