天天看點

從零開始學google地圖API(6)--持續擷取位置資訊

上一節研究了一下粗略定位,下面來稍微精确一些

上一節的getCurrentPosition()可以擷取位置,但隻能擷取一次,這次要介紹的是 watchPosition

看名字都可以猜出,這個是一直監聽對方位置的,并且可以實時更新,如果對方位置發生變化了可以及時顯示

效果如下,隔一段時間就可以感覺到頁面重新整理了一下,其實是在更新位置

從零開始學google地圖API(6)--持續擷取位置資訊
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=false"></script>
<script>
function initialize()
{
 function success(position) {
    var latitude  = position.coords.latitude;
    var longitude = position.coords.longitude;
    var yourmap = {
        center:new google.maps.LatLng(latitude  ,longitude),
        zoom:11,
        mapTypeId:google.maps.MapTypeId.ROADMAP
    };
    var map=new google.maps.Map(document.getElementById("googleMap"), yourmap);
var marker=new google.maps.Marker({
  position:new google.maps.LatLng(latitude  ,longitude),
  });
marker.setMap(map);
var infowindow = new google.maps.InfoWindow({
  content:"我在這裡!"
  });
infowindow.open(map,marker);
  };
function error() {
   alert('地理位置不可用');
  };
var geo_options = {
  enableHighAccuracy: true, 
  maximumAge        : 30000, 
  timeout           : 27000
};

  if ("geolocation" in navigator) {
 navigator.geolocation.watchPosition(success, error,geo_options );
} else
 {
alert('地理位置不可用');
}
};
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
</html>
           

變化到不大…就是多了一個額外參數的定義

var geo_options = {
  enableHighAccuracy: true, //允許高精度定位
  maximumAge        : 30000,  //有效期限
  timeout           : 27000//逾時
};
           

然後函數多了一個參數而已

當然我們這裡沒弄太複雜,其實上一節的getCurrentPostion()也可以傳遞第三個參數,效果也類似,他們之間最大的差別就是執行的次數

由于watch是一直監聽。我們可能後來就不需要監聽了,就可以取消監聽

剛才函數裡面沒有展現,其實watchPostion是會傳回一個watchID的,我們可以通過一個watchID對應到一個監聽的程序并通過clearwatch來取消監聽

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

繼續閱讀