Reputation: 5
i want to create a Map with an easy function. Everytime i click, the existing Marker schould be removed and a new one schould appear at click-position.
Creating new ones works fine, but removing them doesn't work. Here the code, I tried:
var map;
var latitude, longitude;
var marker;
function placeMarker(location) {
marker.setMap(null);
marker = new google.maps.Marker({
map: map,
position: location,
});
latitude = location.lat();
longitude = locaton.lng();
document.getElementById('koordinaten').innerHTML = '<p>' + latitude + '</p>';
}
OK, comment the marker.setMap(null); i can add as much markers as i want, but i want to only have one Marker on the Map.
Can you please help me, how to remove a marker and place a new one?
Thanks
Upvotes: 0
Views: 75
Reputation: 117314
When you run this function the first time, the first line will result in an error, because marker still is undefined
(doesn't have a setMap
-method).
You may catch this case and bypass the first line :
if(typeof marker!=='undefined'){
marker.setMap(null);
}
But a better approach would be to use always the same marker and apply the new position:
function placeMarker(location) {
//when marker is undefined, create a marker
if(typeof marker==='undefined'){
marker = new google.maps.Marker({
map: map
});
}
//set the position
marker.setPosition(location);
latitude = location.lat();
longitude = locaton.lng();
document.getElementById('koordinaten').innerHTML
= '<p>' + latitude + '</p>';
}
Upvotes: 0