支持地理位置API的浏览器会定义navigator.grolocation属性,该属性拥有三个方法:
1,navigator.geolocation.getCurrentPoaidion(); //获取当前地理位置
是异步的,需要接受一个回调函数作为参数(还可以接受第二个参数,当获取失败后执行的回调,第三个参数是配置对象,包括是否需要高精度的位置信息、位置信息的过期时间、允许在多长时间内获取位置信息)
navigator.geolocation.getCurrentPosition(function(pos){
var latitude = pos.coords.latitude;
var longitude = pos.coords.longitude;
alert('您的位置经纬度是:' + latitude + " , " + longitude)
})
//pos.coords.accuracy 表示精度 ‘米’
完整的例子:
HTML:
<div class="elt"></div>
JS:
var elt = document.querySelector('.elt'); function whereami(elt){ var options = { enableHighAccuracy: false, //是否高精度 maximumAge: 300000, //五分钟后 timeout: 15000 //愿意等多长时间 }; if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(success, error, options) } else { elt.innerHTML = '您的浏览器不支持定位' } function error(e) { elt.innerHTML = '定位失败 ' + e.code + ' : ' + e.message } function success(pos){ var msg = '在' + new Date(pos.timestamp).toLocaleString() + '的时候,距离您' + pos.coords.accuracy + '米的地方,经度' + pos.coords.latitude + '纬度' + pos.coords.longitude + ' . '; elt.innerHTML = msg; } }
whereami(elt)
2,navigator.geolocation.watchPosition() //获取当前位置,并不断监视当前位置,位置变化时 调用指定的回调函数
是异步的,需要接受一个回调函数作为参数(跟上面的getCurrentPosition()用法一样)