提交按钮提交时,谷歌地图会移动相同的标记

时间:2011-07-22 13:51:25

标签: google-maps google-maps-markers move

我想在提交按钮后移动相同的标记。我有这样的代码,它在提交按钮后添加另一个点。请帮忙。感谢。

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>

这是正确答案......

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

1 个答案:

答案 0 :(得分:1)

试试这个 在地图声明后声明标记

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