2013-03-21 52 views
1

我試圖在Google地圖上創建單個標記以顯示用戶當前位置。使用下面的代碼,我可以做到這一點,但每次watchPosition刷新時都會創建一個新點。每次添加新點時,如何清除以前的標記?僅使用watchPosition顯示當前位置標記

// Geolocation 
var win = function(position) { 
    var iconimage = new google.maps.MarkerImage('images/current_location_small.png', 
     new google.maps.Size(15, 15), 
     new google.maps.Point(0,0), 
     new google.maps.Point(7, 7) 
    ); 
    var lat = position.coords.latitude; 
    var long = position.coords.longitude; 
    var myLatlng = new google.maps.LatLng(lat, long); 
    var marker = new google.maps.Marker({ 
     position: myLatlng, 
     map: map, 
     icon: iconimage 
    }); 

    marker.setMap(map); 
}; 

var watchID = navigator.geolocation.watchPosition(win); 

回答

3

你可以宣佈你的標記功能外,使用setPosition(LatLng)方法

// Geolocation 
var marker=null; 
var win = function(position) { 

    var lat = position.coords.latitude; 
    var long = position.coords.longitude; 
    var myLatlng = new google.maps.LatLng(lat, long); 
    if(marker==null){ 
     var iconimage = new google.maps.MarkerImage('images/current_location_small.png', 
      new google.maps.Size(15, 15), 
      new google.maps.Point(0,0), 
      new google.maps.Point(7, 7) 
     ); 
     marker = new google.maps.Marker({ 
      position: myLatlng, 
      map: map, 
      icon: iconimage 
     }); 
     marker.setMap(map); 
    }else{ 
     marker.setPosition(myLatlng); 
    } 
}; 

var watchID = navigator.geolocation.watchPosition(win); 
+0

完美 - 謝謝。 – Rob 2013-03-21 04:04:15

+0

很高興爲您提供幫助,以備將來參考'marker.setMap(null)'從地圖中移除標記:) – kevmc 2013-03-21 04:34:10

1

或作爲的setNull的評論指出,這對當時重繪。 當然屏幕閃爍,它在速度重繪GPS更新 刪除,如果線在下面我的代碼,你會不斷地吸取線索

var watchID = navigator.geolocation.watchPosition(function(position) { 

    // Get current position 
    pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); 

    // Redefine current location marker 
    if (typeof(marker) != "undefined") marker.setMap(null); 
    marker = new google.maps.Marker({ 
    position: pos, 
    map: map, 
    title: 'you are here', 
    icon : user 
    },watchOptions); 

}); //end constant watchPosition 
相關問題