我正在建立一个网络应用程序,以便使用地理定位和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);
}
此代码有效但在用户更改位置时会不断添加标记。 我如何才能在当前用户位置只显示一个标记?
答案 0 :(得分:5)
每次调用centerMap
时,只需使用marker.setPosition(myLatlng)
更新其位置,而不是生成新标记。