您的位置:首页 > Web前端 > HTML5

HTML5--Geolocation(地理定位)

2016-12-19 13:21 423 查看
HTML5 Geolocation API 用于获得用户的地理位置。

一、HTML5 - 使用地理定位

getCurrentPosition() 方法可以用来获得用户的位置。

下例是一个简单的地理定位实例,可返回用户位置的经度和纬度:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>地理定位</title> 
</head>
<body>
<p id="demo">点击按钮获取您当前坐标(可能需要比较长的时间获取):</p>
<button onclick="getLocation()">点我</button>
<script>
var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else
{
x.innerHTML="该浏览器不支持获取地理位置。";
}
}

function showPosition(position)
{
x.innerHTML="纬度: " + position.coords.latitude +
"<br>经度: " + position.coords.longitude;
}
</script>
</body>
</html>实例解析:
检测是否支持地理定位
如果支持,则运行 getCurrentPosition() 方法。如果不支持,则向用户显示一段消息。
如果getCurrentPosition()运行成功,则向参数showPosition中规定的函数返回一个coordinates对象
showPosition() 函数获得并显示经度和纬度

注意:上面的例子是一个非常基础的地理定位脚本,不含错误处理。

二、处理错误和拒绝
getCurrentPosition() 方法的第二个参数用于处理错误。它规定当获取用户位置失败时运行的函数。

function showError(error)
{
switch(error.code)
{
case error.PERMISSION_DENIED:
x.innerHTML="用户拒绝对获取地理位置的请求。"
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML="位置信息是不可用的。"
break;
case error.TIMEOUT:
x.innerHTML="请求用户地理位置超时。"
break;
case error.UNKNOWN_ERROR:
x.innerHTML="未知错误。"
break;
}
}错误代码:
Permission denied - 用户不允许地理定位
Position unavailable - 无法获取当前位置
Timeout - 操作超时
三、在地图中显示结果

如需在地图中显示结果,您需要访问可使用经纬度的地图服务,比如谷歌地图或百度地图:
function showPosition(position)
{
var latlon=position.coords.latitude+","+position.coords.longitude;

var img_url="http://maps.googleapis.com/maps/api/staticmap?center="
+latlon+"&zoom=14&size=400x300&sensor=false";
document.getElementById("mapholder").innerHTML="<img src='"+img_url+"'>";
}在上例中,我们使用返回的经纬度数据在谷歌地图中显示位置(使用静态图像)。

下面的示例向您演示如何使用脚本来显示带有标记、缩放和拖曳选项的交互式地图。
<div id="mapholder"></div>
<script src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function showPosition(position)
{
lat=position.coords.latitude;
lon=position.coords.longitude;
latlon=new google.maps.LatLng(lat, lon)
mapholder=document.getElementById('mapholder')
mapholder.style.height='250px';
mapholder.style.width='500px';

var myOptions={
center:latlon,zoom:14,
mapTypeId:google.maps.MapTypeId.ROADMAP,
mapTypeControl:false,
navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}
};
var map=new google.maps.Map(document.getElementById("mapholder"),myOptions);
var marker=new google.maps.Marker({position:latlon,map:map,title:"You are here!"});
}四、给定位置的信息
1. getCurrentPosition() 方法 - 返回数据
若成功,则 getCurrentPosition() 方法返回对象。始终会返回
latitude、longitude 以及 accuracy 属性。如果可用,则会返回其他下面的属性。

属性描述
coords.latitude十进制数的纬度
coords.longitude十进制数的经度
coords.accuracy位置精度
coords.altitude海拔,海平面以上以米计
coords.altitudeAccuracy位置的海拔精度
coords.heading方向,从正北开始以度计
coords.speed速度,以米/每秒计
timestamp响应的日期/时间
2. watchPosition() - 返回用户的当前位置,并继续返回用户移动时的更新位置(就像汽车上的 GPS)。

    clearWatch() - 停止 watchPosition() 方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: