What I want to do is,
on my map, when I click somewhere on the map, it shows a marker on the point, then I click different point on the map then it shows a another mark
To remove a marker just setMap(null) it.
<html>
<style type="text/css">
#map_canvas {
height: 760px;
width: 1100px;
position: static;
top: 100px;
left: 200px;
}
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var oldMarker;
function initialize() {
var latlng = new google.maps.LatLng(42.55308, 9.140625);
var myOptions = {
zoom: 2,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false,
mapTypeControl: false,
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
function placeMarker(location) {
marker = new google.maps.Marker({
position: location,
map: map
animation: google.maps.Animation.DROP,
});
if (oldMarker != undefined){
oldMarker.setMap(null);
}
oldMarker = marker;
map.setCenter(location);
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="1500px; 1000px"></div>
</body>
</html>
Another solution is to move a marker, for that you just user marker.setPosition(). (thanks kjy112 for the warning :)
<html>
<style type="text/css">
#map_canvas {
height: 760px;
width: 1100px;
position: static;
top: 100px;
left: 200px;
}
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var marker;
function initialize() {
var latlng = new google.maps.LatLng(42.55308, 9.140625);
var myOptions = {
zoom: 2,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false,
mapTypeControl: false,
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
function placeMarker(location) {
if (marker == undefined){
marker = new google.maps.Marker({
position: location,
map: map,
animation: google.maps.Animation.DROP,
});
}
else{
marker.setPosition(location);
}
map.setCenter(location);
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="1500px; 1000px"></div>
</body>
</html>
Every time placemarker()
is ran, it creates a new marker.
You need to create the marker once outside of the placemarker function and after that, inside placemarker, use marker.setPosition().