0
点赞
收藏
分享

微信扫一扫

Geolocation(地理定位)

大家好,今天我们来看一下html中的地理定位。这个大家在网页中可能会看到获取你的位置,然后对你进行推送内容等一些操作。这个特性是来自于H5.

HTML5 Geolocation API 用于获得用户的地理位置。鉴于该特性可能侵犯用户的隐私,除非用户同意,否则用户位置信息是不可用的。

​navigator.geolocation.getCurrentPosition(showPosition);​

getCurrentPosition() 方法 - 返回数据

若成功,则 getCurrentPosition() 方法返回对象。

始终会返回 latitude、longitude 以及 accuracy 属性。

如果可用,则会返回其他下面的属性。

属性

描述

coords.latitude

十进制数的纬度

coords.longitude

十进制数的经度

coords.accuracy

位置精度

coords.altitude

海拔,海平面以上以米计

coords.altitudeAccuracy

位置的海拔精度

coords.heading

方向,从正北开始以度计

coords.speed

速度,以米/每秒计

timestamp

响应的日期/时间

watchPosition() - 返回用户的当前位置,并继续返回用户移动时的更新位置(就像汽车上的 GPS)。

clearWatch() - 停止 watchPosition() 方法

​navigator.geolocation.watchPosition(showPosition);​

看案例

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>定位</title>
</head>
<body>
<body>
<p id="demo">点击按钮获取您当前坐标(可能需要比较长的时间获取):</p>
<button onclick="getLocation()">点我</button>
<script>var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition2, showError);
}
else
{
x.innerHTML="该浏览器不支持获取地理位置。";
}
}
//在地图中显示结果1
function showPosition1(position)
{
x.innerHTML="纬度: " + position.coords.latitude +
"<br>经度: " + position.coords.longitude;
}
//在地图中显示结果2
function showPosition2(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+"'>";
}
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;
}
}
</script>
</body>
</body>
</html>

运行结果:

Geolocation(地理定位)_git

Geolocation(地理定位)_git_02

实例解析:

  • 检测是否支持地理定位
  • 如果支持,则运行 getCurrentPosition() 方法。如果不支持,则向用户显示一段消息。
  • 如果getCurrentPosition()运行成功,则向参数showPosition中规定的函数返回一个coordinates对象
  • showPosition() 函数获得并显示经度和纬度

由此可见:

HTML Geolocation(地理定位)用于定位用户的位置。

定位用户的位置

html Geolocation API用于获得用户的地理位置

鉴于该特性可能低侵犯用户的隐私,除非用户同意,否则用户位置信息是不可用的。

举报

相关推荐

0 条评论