Geolocation API JavaScript访问用户的当前位置信息

Geolocation API在浏览器中的实现是navigator.geolocation对象,常用的有以下方法。

1、第一个方法是getCurrentPosition()

调用这个方法就会触发请求用户共享地理定位信息的对话框。比如在火狐中的对话框:

这个方法接收3个参数:成功回调函数、可选的失败回调函数和可选的选项对象。

成功回调函数会接收一个Position对象参数,有两个属性:coords和timestamp。

coords对象中包含下列与位置相关的信息。

  1. latitude,十进制纬度
  2. longitude,十进制经度
  3. accuracy,精度,米

有些浏览器还会提供海拔/海拔精度/速度等信息。Web常用的是纬度和经度。

比如显示用户的位置:

navigator.geolocation.getCurrentPosition(function(position){
    $(".content div.item2").text("你的位置在:北纬"+position.coords.latitude+" 东经"+position.coords.longitude);
});

失败回调函数,会接收一个对象,包含两个属性,message和code,前者保存错误文本消息,后者保存错误码,有1—用户拒绝共享,2-位置无效,3-超时。大多数情况下将错误信息保存在日志文件中。演示:

    navigator.geolocation.getCurrentPosition(function(position){
        $(".content div.item2").text("你的位置在:北纬"+position.coords.latitude+" 东经"+position.coords.longitude);
    },function(error){
        $(".content div.item2").text(error.code+","+error.message);
    });

在Chrome中拒绝共享时拒绝:

会显示:错误码1,信息是用户拒绝共享。

③第三个参数是选项对象,用于设定信息的类型,可以设置的选项有三个:

  1. enableHighAccuracy,布尔值,尽可能使用最精确的位置信息。
  2. timeout,等待位置信息的最长时间,毫秒
  3. maximumAge,上次取得的坐标信息的有效时间,毫秒,如果时间到则重新获取坐标信息。

如:

    navigator.geolocation.getCurrentPosition(function(position){
        $(".content div.item2").text("你的位置在:北纬"+position.coords.latitude+" 东经"+position.coords.longitude);
    },function(error){
        $(".content div.item2").text(error.code+","+error.message);
    },{
        enableHighAccuracy:false,
        timeout:1000,
        maximumAge:5000
    });

不需要特别精确的境况下,建议enableHighAccuracy为false,否则耗时耗电。maximumAge值可以是Infinity,表示始终使用上次的坐标信息。

2、另一个方法,watchPosition(),跟踪用户的位置。接收的参数与getCurrentPosition()一致。

该方法第一次取得位置信息后,会就地等待系统发出位置改变的信号。

可以调用clearWatch()方法取消跟踪。

内容来源于JavaScript高级程序设计。

posted @ 2016-12-26 11:25  ZhangCui  阅读(695)  评论(0编辑  收藏  举报