地理位置情報と GPS を使用してユーザーの現在位置にマーカーを表示するために、Web アプリを構築しています。これが私のコードです
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);
}
このコードは機能しますが、ユーザーが場所を変更するとマーカーが追加され続けます。現在のユーザーの場所にマーカーを 1 つだけ表示するにはどうすればよいですか?