HTML5 Geolocation(地理位置)

HTML5 Geolocation(地理位置)、是用来定位用户的位置的。

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

请使用getCurrentPosition()方法来获取用户的地理位置信息

提示:HTML5 Geolocation(地理位置)对于使用GPS的设备,对地理位置的定位更加精确:如:手机。

实例:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta charset="utf-8" />
<style type="text/css"></style>
<script type="text/javascript" src="Css/jquery-2.1.4.js"></script>
<script type="text/javascript"></script>
</head>
<body>
<p>点击按钮获取您的地理位置信息(可能需要比较长的时间获取):<span id="result"></span></p>
<button onclick="getLocation()">点击按钮</button>
<script>
var x = document.getElementById("result");
function getLocation() {
if (navigator.geolocation) {//检测浏览器是否支持geolocation(地理位置)
navigator.geolocation.getCurrentPosition(showLocation,showError);//如果运行成功,则使用getCurrentLocation()方法的参数规定中的函数返回一个coordinates对象
}
else {
x.innerHTML = "Sorry!,您浏览器不支持HTML5的geolocation";//您浏览器不支持HTML5的geolocation
}
}
function showLocation(weizi) {//函数获取地理位置的纬度和经度
x.innerHTML = "纬度:" + weizi.coords.lataitude + " <br />经度:" + weizi.coords.longitude;
}
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>
</html>

原文地址:https://www.cnblogs.com/melao2006/p/4980870.html