您好,欢迎访问一九零五行业门户网

html5之使用地理定位的代码分享

1)使用地理定位:
  通过navigator.geolocation访问地理定位功能,返回一个geolocation对象;
  1.1)geolocation对象成员:
       getcurrentposition(callback,errorcallback,options)——获取当前位置;
       watchposition(callback,error,options)——开始监控当前位置;
       clearwatch(id)——停止监控当前位置;
  1.1.1)浏览器调用getcurrentposition的callback函数的参数时,会传入一个提供位置详情的position对象;
        position对象成员:
        coords——返回当前位置的坐标,即coordinates对象;
        timestamp——返回获取坐标信息的时间;
        coordinates对象成员:
        latitude——返回用十进制表示的纬度;
        longitude——返回用十进制表示的经度;
        altitude——返回用米表示的海拔高度;
        accuracy——返回用米表示的坐标精度;
        altitudeaccuracy——返回用米表示的海拔精度;
        heading——返回用度表示的行进方向;
        speed——返回用米/秒表示的行进速度;
2)处理地理定位错误:
   getcurrentposition(callback,errorcallback,options)方法的第二个参数,它让我们可以指定一个函数,在获    取位置发生错误时调用它。此函数会获得一个positionerror对象;
   positionerror对象成员:
   code——返回代表错误类型的代码;
       =1——用户未授权使用地理定位功能;
       =2——不能确定位置;
       =3——请求位置的尝试已超时;
   message——返回描述错误的字符串;
3)指定地理定位选项:
   getcurrentposition(callback,errorcallback,options)方法提供的第三个参数是一个positionoptions对象。
   positionoptions对象的成员:
   enablehighaccuracy——告诉浏览器我们希望得到可能的最佳结果;
   timeout——限制请求位置的事件,设置多少毫秒后会报告一个超时错误;
   maximumage——告诉浏览器我们愿意接受缓存过的位置,只要它不早于指定的毫秒数;
4)监控位置:
   watchposition方法不断获得关于位置的更新。所需参数与getcurrentposition方法相同,工作方式也一样。
   区别在于:随着位置发生改变,回调函数会被反复地调用。
table{ border-collapse: collapse; } th,td{ padding: 4px; } th{ text-align: right; }
<table border="1"> <tr> <th>经度:</th><td id="longitude">-</td> <th>纬度:</th><td id="latitude">-</td> </tr> <tr> <th>海拔高度:</th><td id="altitude">-</td> <th>坐标精度:</th><td id="accuracy">-</td> </tr> <tr> <th>海拔精度:</th><td id="altitudeaccuracy">-</td> <th>行进方向:</th><td id="heading">-</td> </tr> <tr> <th>速度:</th><td id="speed">-</td> <th>时间:</th><td id="timestamp">-</td> </tr> <tr> <th>错误类型:</th><td id="errcode">-</td> <th>错误信息</th><td id="errormessage">-</td> </tr> </table><pre name="code" class="html"> <button id="pressme">cancel watch</button>
var options={ enablehighaccuracy:false, timeout:2000, maximumage:30000 } var watchid=navigator.geolocation.watchposition(displayposition,handleerror,options) document.getelementbyid("pressme").onclick=function(e){ navigator.geolocation.clearwatch(watchid); } function displayposition(pos){ var properties=["longitude","latitude","altitude","accuracy","altitudeaccuracy","heading","speed"]; for(var i=0;i<properties.length;i++){ var value=pos.coords[properties[i]]; document.getelementbyid(properties[i]).innerhtml=value; } document.getelementbyid("timestamp").innerhtml=pos.timestamp; } function handleerror(err){ document.getelementbyid("errcode").innerhtml=err.code; document.getelementbyid("errmessage").innerhtml=err.message; }
以上就是html5之使用地理定位的代码分享的详细内容。
其它类似信息

推荐信息