html5接口getCurrentPosition函数
html5接口getCurrentPosition函数
1、该函数用于定位用户的位置,从而获取用户信息,以便分析用户来源行为等。
2、因该函数会获取用户位置,可能会侵犯用户的隐私,所以使用前要取得用户的同意,即会弹出询问,是否同意。
3、服务协议一定要https协议,http协议是受到限制的,建议服务协议设置成https协议,否则解决限制问题比较麻烦。
4、实现定位逻辑:
(1)检测浏览器是否支持地理定位,判断 navigator.geolocation 是否存在。
(2)如果支持,则运行 Geolocation 对象的 getCurrentPosition() 方法navigator.geolocation.getCurrentPosition(showPosition,showError),如果不支持,则向用户显示一段消息。
(3)如果 getCurrentPosition() 运行成功,则会回调showPosition函数,并向showPosition函数传入coordinates 对象。
(4)showPosition() 函数根据传入的coordinates 对象来获得并显示经度和纬度。
(5)如果 getCurrentPosition() 运行失败,则会回调 showError 函数,并向 showError函数传入错误代码。
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition,showError);
} else {
alert("你的浏览器不支持获取地理位置信息。");
}
}
function showPosition(position) {
alert("Latitude: " + position.coords.latitude + "<br />Longitude: " + position.coords.longitude);
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
alert("用户不允许地理定位");
break;
case error.POSITION_UNAVAILABLE:
alert("无法获取当前位置");
break;
case error.TIMEOUT:
alert("获取位置超时");
break;
case error.UNKNOWN_ERROR:
alert("未知的错误");
break;
}
}
</script>5、getCurrentPosition()方法返回的位置对象始终会包含有:latitude、longitude以及accuracy属性的值,它包含的所有属性列表如下:
属性 | 说明 |
coords.latitude | 十进制数的纬度 |
coords.longitude | 十进制数的经度 |
coords.accuracy | 定位位置的精度 |
coords.altitude | 海拔,海平面以上以米计 |
coords.altitudeAccuracy | 定位位置的海拔精度 |
coords.heading | 方向,从正北开始以度计 |
coords.speed | 速度,以米/每秒计 |
timestamp | 定位请求响应的时间戳 |
