地理定位(Geolocation)API让我们可以获取用户当前地理位置的信息(或者至少是正在运行浏览器的系统的位置)。它不是HTML5规范的一部分,但经常被归组到与HTML5相关的新功能中。1. 使用地理定位我们通过全局属性 navigator.geolocation 访问地理定 ...
地理定位(Geolocation)API让我们可以获取用户当前地理位置的信息(或者至少是正在运行浏览器的系统的位置)。它不是HTML5规范的一部分,但经常被归组到与HTML5相关的新功能中。
1. 使用地理定位
我们通过全局属性 navigator.geolocation 访问地理定位功能,它会返回一个 Geolocation对象。
获取当前位置
顾名思义,getCurrentPosition方法能获得当前的位置,不过位置信息不是由函数自身返回的。我们需要提供一个成功的回调函数,它会在位置信息可用时触发(这样做考虑到了请求位置和信息变得可用之间可能会有延迟)。下面的示例展示了如何使用这个方法获得位置信息:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>获取当前位置</title> <style type="text/css"> table {border-collapse: collapse;} th,td {padding: 4px;} th {text-align: right;} </style></head><body><table border="1"> <tr> <th>Longitude:</th><td id="longitude">-</td> <th>Latitude:</th><td id="latitude">-</td> </tr> <tr> <th>Altitude:</th><td id="altitude">-</td> <th>Accuracy:</th><td id="accuracy">-</td> </tr> <tr> <th>Altitude Accuracy:</th><td id="altitudeAccuracy">-</td> <th>Heading:</th><td id="heading">-</td> </tr> <tr> <th>Speed:</th><td id="speed">-</td> <th>Time Stamp:</th><td id="timestamp">-</td> </tr></table><script type="application/javascript"> navigator.geolocation.getCurrentPosition(displayPosition); function displayPosition(pos){ var propertis = ["longitude","latitude","altitude","accuracy", "altitudeAccuracy","heading","speed"]; for(var i=0;i<propertis.length;i++){ var value = pos.coords[propertis[i]]; document.getElementById(propertis[i]).innerHTML = value; } document.getElementById("timestamp").innerHTML = pos.timestamp; }</script></body></html>
原标题:【高级功能】使用地理定位
关键词:地理
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。