谷歌地图API watchPosition

man*_*man 3 geolocation google-maps-api-3

我正在建立一个网络应用程序,以便使用地理定位和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);

 }
Run Code Online (Sandbox Code Playgroud)

此代码有效但在用户更改位置时会不断添加标记.我如何才能在当前用户位置只显示一个标记?

Joh*_*nny 5

每次centerMap调用时都不会生成新标记,只需更新其位置即可marker.setPosition(myLatlng).