从零开始学google地图API(6)--持续获取位置信息

上一节研究了一下粗略定位,下面来稍微精确一些
上一节的getCurrentPosition()可以获取位置,但只能获取一次,这次要介绍的是 watchPosition
看名字都可以猜出,这个是一直监听对方位置的,并且可以实时更新,如果对方位置发生变化了可以及时显示

效果如下,隔一段时间就可以感觉到页面刷新了一下,其实是在更新位置
在这里插入图片描述

<!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//超时
};

然后函数多了一个参数而已

navigator.geolocation.watchPosition(success, error,geo_options );

当然我们这里没弄太复杂,其实上一节的getCurrentPostion()也可以传递第三个参数,效果也类似,他们之间最大的区别就是执行的次数

由于watch是一直监听。我们可能后来就不需要监听了,就可以取消监听
刚才函数里面没有体现,其实watchPostion是会返回一个watchID的,我们可以通过一个watchID对应到一个监听的进程并通过clearwatch来取消监听

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

猜你喜欢

转载自blog.csdn.net/azraelxuemo/article/details/106804388