Sam Creamer
Sam Creamer

Reputation: 5361

google maps apiv3 marker replace old

I have a little function that adds a marker and info window when it is clicked. However, when I click on a new location, the old one remains. I'd like it to be replaced by the new one. Here is my code:

function MapInitialize() {

            var mapOptions = {
            zoom: 4,
            center: new google.maps.LatLng(43,-77),
            mapTypeId: google.maps.MapTypeId.ROADMAP
            }

            var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
        google.maps.event.addListener(map, 'click', function(event) {
            var marker = new google.maps.Marker({
                position: event.latLng,
                map: map
        })
        var infowindow = new google.maps.InfoWindow({
                content: 'Content Here'
            });
            infowindow.open(map,marker);
});
}

Thanks!

Upvotes: 0

Views: 218

Answers (1)

geocodezip
geocodezip

Reputation: 161334

Delete the old marker before creating the new one:

var marker = null;
function MapInitialize() {

            var mapOptions = {
            zoom: 4,
            center: new google.maps.LatLng(43,-77),
            mapTypeId: google.maps.MapTypeId.ROADMAP
            }

            var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
        google.maps.event.addListener(map, 'click', function(event) {
            if (marker && marker.setMap) marker.setMap(null);
            marker = new google.maps.Marker({
                position: event.latLng,
                map: map
        })
        var infowindow = new google.maps.InfoWindow({
                content: 'Content Here'
            });
            infowindow.open(map,marker);
});
}

Upvotes: 1

Related Questions