Search code examples
google-mapsgoogle-maps-markersmove

google maps move same marker when submit the button submit


I want to move same marker after submit the button. I have a code like this, it's add another point after submit the button. please help. thanks.

http://project-amma.info/map6.html

<script type="text/javascript">
    var geocoder;
    var map;

    function initialize() {
        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(6.5,80.0);
        var myOptions = {
        zoom: 12,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    }

    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);
        }
        });
    }
</script>

<body onload="initialize()">
<div>
<input id="address" type="textbox" value="" />
<input type="button" value="Geocode" onclick="codeAddress()" />
</div>
<div id="map_canvas" style="height:90%">
</div>
</body>

here is the correct answer...

var marker = null;

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);

            if(marker == null){
                marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
                });
            }else
                marker.setPosition(results[0].geometry.location);
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
        });
    }

Solution

  • try this declare marker after map declare

    if(marker == null){
        marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
        });
    }else
        marker.setPosition(results[0].geometry.location);