Follow the code:
function initAutocomplete() {
debugger
var markers = [];
var latitude = parseFloat('@Model.Latitude'); // -23.4811396
var longitude = parseFloat('@Model.Longitude'); // -46.3676736
var myLatLng = {lat: latitude, lng: longitude};
var map = new google.maps.Map(document.getElementById('map-edit'), {
center: { lat: latitude , lng: longitude },
zoom: 11,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker_old = new google.maps.Marker({ // <-----marcador antigo
position: myLatLng,
map: map,
title: '@Model.GoogleMaps_Address'
});
markers.push(marker_old);
var input = document.getElementById('pac-input-edit');
var autocomplete = new google.maps.places.Autocomplete(input, { types: ['address'] });
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function () {
debugger
markers = []; //<------ limpar marcador antigo
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
$('#pac-input-create').val('');
Alert("Endereço inválido");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
}
When doing new search, it is not removing old marker. Any solution ? Here is the result: