Google maps api 3 谷歌地图API监视位置

Google maps api 3 谷歌地图API监视位置,google-maps-api-3,geolocation,Google Maps Api 3,Geolocation,Im正在构建一个web应用程序,以便使用地理定位和GPS在用户当前位置显示标记。这是我的密码 var marker; $(window).load(function() { myOptions = { zoom: 20, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var w

Im正在构建一个web应用程序,以便使用地理定位和GPS在用户当前位置显示标记。这是我的密码

var marker;
 $(window).load(function() {
    myOptions = { zoom: 20, mapTypeId: google.maps.MapTypeId.ROADMAP };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    var watchId = navigator.geolocation.watchPosition(centerMap); 
 });



function centerMap(location)
{
var myLatlng = new google.maps.LatLng(location.coords.latitude,location.coords.longitude);
map.setCenter(myLatlng);
map.setZoom(15);

    $("#lat").text("Latitude : " + location.coords.latitude);
    $("#lon").text("Longitude : " + location.coords.longitude);
    //show current location on map
    marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    zIndex:1
    });

navigator.geolocation.clearWatch(watchId);

 }
这段代码可以工作,但随着用户更改位置,它会不断添加标记。
如何在当前用户位置仅显示一个标记?

每次调用
centerMap
时,只需使用
marker.setPosition(myLatlng)
更新其位置即可,而无需生成新的标记