HTML5 – 使用地理定位
请使用 getCurrentPosition() 方法来获得用户的位置。
下例是一个简单的地理定位实例,可返回用户位置的经度和纬度。
实例
<script>
var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition)
;
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
x.innerHTML="Latitude: " + position.coords.latitude +
"<br />Longitude: " + position.coords.longitude;
}
</script>
例子解释:
- 检测是否支持地理定位
- 如果支持,则运行 getCurrentPosition() 方法。如果不支持,则向用户显示一段消息。
- 如果getCurrentPosition()运行成功,则向参数showPosition中规定的函数返回一个coordinates对象
- showPosition() 函数获得并显示经度和纬度
上面的例子是一个非常基础的地理定位脚本,不含错误处理。
getCurrentPosition() 方法 – 返回数据
若成功,则 getCurrentPosition() 方法返回对象。始终会返回 latitude、longitude 以及 accuracy 属性。如果可用,则会返回其他下面的属性。
属性 | 描述 |
---|---|
coords.latitude | 十进制数的纬度 |
coords.longitude | 十进制数的经度 |
coords.accuracy | 位置精度 |
coords.altitude | 海拔,海平面以上以米计 |
coords.altitudeAccuracy | 位置的海拔精度 |
coords.heading | 方向,从正北开始以度计 |
coords.speed | 速度,以米/每秒计 |
timestamp | 响应的日期/时间 |
Geolocation 对象 – 其他有趣的方法
watchPosition() – 返回用户的当前位置,并继续返回用户移动时的更新位置(就像汽车上的 GPS)。
clearWatch() – 停止 watchPosition() 方法
下面的例子展示 watchPosition() 方法。您需要一台精确的 GPS 设备来测试该例(比如 iPhone):
实例
<script>
var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.watchPosition(showPosition)
;
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
x.innerHTML="Latitude: " + position.coords.latitude +
"<br />Longitude: " + position.coords.longitude;
}
</script>