Reputation: 351
I am using Shreerang Patwardhan's code for Javascript geocoding. However, I am having difficulities regarding the removal of the previous marker when entering a new address. I have Googled and experimented but I just can't get the result I want. I want the previous marker removed/hidden when a new marker gets placed.
HTML:
<html>
<head>
<title>Google Maps API v3 Example : Geocoding Simple</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
</script>
</head>
<body onload="initialize()">
<div align="center" style="height: 30px; width: 430px">
<input id="address" type="textbox">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map" style="height:200px; width: 430px"></div>
</body>
</html>
Javascript:
var geocoder;
var map;
function initialize()
{
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById("map"),
{
zoom: 8,
center: new google.maps.LatLng(22.7964,79.5410),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function codeAddress()
{
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker(
{
map: map,
position: results[0].geometry.location
});
}
else
{
alert("Geocode was not successful for the following reason: " + status);
}
});
}
The code that I'm using is the same code as in this JS Fiddle:
Upvotes: 3
Views: 3386
Reputation: 4876
You need to do an marker.setMap(null);
marker is the reference to previous marker
if(marker)
marker.setMap(null)
https://jsfiddle.net/F4Sd2/637/ is the working fiddle
Upvotes: 1