html5 geolocation

定位用户的位置

html5 geolocation api 用于获得用户的地理位置。

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

注意: geolocation(地理定位)对于拥有 gps 的设备,比如 iphone,地理定位更加精确。

geography 地理; location 位置; geo+location 地理位置; current 现在;

getcurrentposition() 方法 – 返回数据

t若成功,则 getcurrentposition() 方法返回对象。始终会返回 latitude、longitude 以及 accuracy 属性。如果可用,则会返回其他下面的属性。

属性 描述
coords.latitude 十进制数的纬度
coords.longitude 十进制数的经度
coords.accuracy 位置精度
coords.altitude 海拔,海平面以上以米计
coords.altitudeaccuracy 位置的海拔精度
coords.heading 方向,从正北开始以度计
coords.speed 速度,以米/每秒计
timestamp 响应的日期/时间

html5 – 使用地理定位

请使用 getcurrentposition() 方法来获得用户的位置。

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

<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>geolocation</title>
</head>
<body>
	<button onclick="getlocation()">点击获取地理位置</button>
	<p>数据信息:</p>
	<p id="demo"></p>
	<script>
		var x=document.getelementbyid("demo");

		function getlocation()
		{
                        //检测是否支持地理定位
			if (navigator.geolocation)
			{
				navigator.geolocation.getcurrentposition(updatpos,errorloca);
			}
			else
			{
				x.innerhtml="该浏览器不支持获取地理位置。";
			}
		}
		//处理数据并显示
		function updatpos(position){
	            var latitude = position.coords.latitude;//十进制单位
	            var longitude = position.coords.longitude;//十进制单位
	            var accuracy = position.coords.accuracy;//以m为单位制定纬度和经度与实际位置的差距
	            var timestamp = position.timestamp;//时间戳
 		    var date = new date(timestamp);//时间格式
            
	            console.log('经度坐标' + latitude.tofixed(2)); //保留两位小数
	            console.log('纬度坐标' + longitude.tofixed(2));
	            console.log('准确度' + accuracy);
	            console.log('获取位置数据的时间' + date);

	            x.innerhtml = "纬度: " + latitude.tofixed(2) + "<br>经度: " + longitude.tofixed(2);   
   		}    
		function errorloca(error){
	    	    var str = "";
	    	    switch(error.code){
	    		case 0:
	    		str ='位置信息获取失败,失败原因'+error.message;break;
                    case 1://错误编码 permission_denied
                    str ='用户拒绝共享其位置信息';break;
                    case 2://错误编码 position_unavailable
                    str = '尝试获取用户位置数据,但失败了' ;break;
                    case 3://错误编码 timeout
                    str = '尝试获取用户的位置数据超时' ;break;
                }
                console.log(str);
                console.warn('error(' + error.code + '): ' + error.message);
                x.innerhtml = str;   
            }
	</script>
</body>
</html>

实例解析:

  • 检测是否支持地理定位
  • 如果支持,则运行 getcurrentposition() 方法。如果不支持,则向用户显示一段消息。
  • 如果getcurrentposition()运行成功,则向参数updatpos中规定的函数返回一个position参数
  • 如果getcurrentposition()运行失败,则向参数errorloca中规定的函数返回一个error参数
  • updatpos() 函数获得并显示经度和纬度
  • errorloca() 函数提示错误信息

geolocation 对象 – 其他有趣的方法

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

clearwatch() – 停止 watchposition() 方法

下面的例子展示 watchposition() 方法。您需要一台精确的 gps 设备来测试该例(比如 iphone):

实例

var x=document.getelementbyid("demo");
function getlocation()
{
    if (navigator.geolocation)
    {
        navigator.geolocation.watchposition(showposition);
    }
    else
    {
        x.innerhtml="该浏览器不支持获取地理位置。";
    }
}
function updatpos(position)
{
    x.innerhtml="纬度: " + position.coords.latitude + 
    "<br>经度: " + position.coords.longitude; 
}

遇到问题以及解决方案

本机运行代码时,默认启动chrome浏览器,每次点击获取地理位置按钮时,反应很慢需要等待许久。

得到报错如下图:

通过查阅资料了解到失败的几种原因。

chrome控制台提示的错误:network location provider at ” : no response received.

chrome浏览器接入的定位服务在国外,有较大的限制,也会造成定位失败,且失败率较高。

换成系统自带的ie浏览器,完美运行

再尝试使用火狐浏览器运行,也成功定位

定位出现失败的原因

1. 第一种情况

浏览器不支持原生定位接口,如ie较低版本的浏览器,message字段包含browser not support html5 geolocation信息。

2. 第二种情况

用户禁用了定位权限,需要用户开启定位权限,message字段包含geolocation permission denied

3. 第三种情况

浏览器禁止了非安全域的定位请求,比如chrome、ios10已经陆续禁止,需要升级站点到https,message字段包含geolocation permission denied信息。**注意:**chrome不会禁止localhost域名http协议下的定位。

4. 第四种情况

浏览器定位超时,包括原生的超时,可以适当增加超时属性的设定值以减少这一现象。某个别浏览器本身对定位接口的友好程度较弱,也会超时返回失败,message字段包含geolocation time out信息。

5. 第五种情况

chrome、firefox以及一些套壳浏览器接入的定位服务在国外,有较大的限制,也会造成定位失败,且失败率较高。