个性化阅读
专注于IT技术分析

HTML5地理位置

本文概述

Geolocation是最好的HTML5 API之一, 用于识别Web应用程序的用户地理位置。

HTML5的这一新功能使你可以导航当前网站访问者的纬度和经度坐标。这些坐标可以通过JavaScript捕获并发送到服务器, 服务器可以显示你在网站上的当前位置

大多数地理位置服务都使用网络路由地址(例如IP地址, RFID, WIFI和MAC地址)或内部GPS设备来识别用户的位置。

提示:要完全理解Geolocation API的概念, 你必须具有一些JavaScript知识。

用户隐私

用户的位置与隐私有关, 因此地理定位API通过在获取位置之前获得用户的许可来保护用户的隐私。地理位置API发送一个通知提示框, 用户可以允许或拒绝它, 如果用户允许, 则只会标识他的位置。

注意:你的浏览器必须支持地理位置才能将其用于Web应用程序。尽管大多数浏览器和移动设备都支持Geolocation API, 但该API仅可用于HTTPS请求。

地理位置对象

Geolocation API与navigation.geolocation对象一起使用。它的只读属性返回一个Geolocation对象, 该对象标识用户的位置, 并可以基于用户的位置生成自定义结果。

句法:

geo=navigator. geolocation;

如果存在此对象, 则可以获取地理位置服务。

地理位置方法

Geolocation API使用以下三种Geolocation接口方法:

方法 描述
getCurrentPosition() 它标识设备或用户的当前位置, 并返回带有数据的位置对象。
watchPosition() 只要设备位置更改, 就返回一个值。
clearWatch() It cancels the previous watchPosition() call

检查浏览器支持

navigator.geolcation对象的geolocation属性有助于确定浏览器对Geolocation API的支持。

<!DOCTYPE html>
<html>
<head>
	<title>Geolocation API</title>
</head>
<body>
  <h1>Find your Current location</h1>
<button onclick="getlocation()">Click me</button>
<div id="location"></div>
<script>
	var x= document.getElementById("location");
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
    function getlocation() {
    	if(navigator.geolocation){
    		alert("your browser is supporting Geolocation API")
    	}
    	else
    	{
    		alert("Sorry! your browser is not supporting")
    	}
    }
</script>
</body>
</html>

立即测试

获取用户的当前位置

要获取用户的当前位置, 请使用navigator.geolocation对象的getCurrentPosition()方法。此方法接受三个参数:

  • 成功:成功的回调函数, 用于获取用户的位置
  • 错误:一个错误回调函数, 该函数将“位置错误”对象作为输入。
  • options:定义用于获取位置的各种选项。

以下示例将返回访问者当前位置的经度和纬度。

<!DOCTYPE html>
<html>
<head>
<title>Geolocation API</title>
</head>
<body>
  <h1>Find your Current location</h1>
<button onclick="getlocation()">Click me</button>
<div id="location"></div>
<script>
	var x= document.getElementById("location");
    function getlocation() {
    	if(navigator.geolocation){
    		navigator.geolocation.getCurrentPosition(showPosition)
    	  }
    	else
    	{
             alert("Sorry! your browser is not supporting")
         } }
     
     function showPosition(position){
       var x = "Your current location is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " +    position.coords.longitude + ")";
                document.getElementById("location").innerHTML = x;
     }
</script>
</body>
</html>

立即测试

说明:

  • 首先检查浏览器支持
  • 使用getCurrentPosition()获取当前位置
  • 使用showPosition()方法获取纬度和经度值, 该方法是getCurrentPosition()的回调方法。

处理错误和拒绝:使用错误回调函数

getCurrentPosition的第二个参数是错误的回调函数。它是一个可选参数, 用于在获取用户位置时处理错误和拒绝用户。

以下是调用错误回调函数的可能选项:

  • 发生未知的随机错误
  • 如果用户拒绝共享位置
  • 位置信息不可用
  • 位置请求超时。

function showError(error) {
     	switch(error.code){
     		case error.PERMISSION_DENIED:
			alert("User denied the request for Geolocation API.");
			break;
		case error.POSITION_UNAVAILABLE:
			alert("USer location information is unavailable.");
			break;
		case error.TIMEOUT:
			alert("The request to get user location timed out.");
			break;
		case error.UNKNOWN_ERROR:
			alert("An unknown error occurred.");
			break;
	}
     	}

立即测试

在Google地图上显示位置

到目前为止, 我们已经看到了如何使用纬度和经度值显示你的位置, 但这还不够。因此, 我们还可以使用此API在Google地图上显示确切位置。

以下示例显示了使用Google Map的位置。

<!DOCTYPE html> 
<html> 
    <head> 
      <title>Geolocation API</title> 
     </head> 
    <body> 
       <h2>Find Your Location in below Map</h2> 
        <button onclick="getlocation();"> Show Position</button> 
        <div id="demo" style="width: 600px; height: 400px; margin-left: 200px;"></div> 
       
        <script src="https://maps.google.com/maps/api/js?sensor=false"> </script> 
        
        <script type="text/javascript"> 
        function getlocation(){ 
            if(navigator.geolocation){ 
                navigator.geolocation.getCurrentPosition(showPos, showErr); 
            }
            else{
                alert("Sorry! your Browser does not support Geolocation API")
            }
        } 
        //Showing Current Poistion on Google Map
        function showPos(position){ 
            latt = position.coords.latitude; 
            long = position.coords.longitude; 
            var lattlong = new google.maps.LatLng(latt, long); 
            var myOptions = { 
                center: lattlong, zoom: 15, mapTypeControl: true, navigationControlOptions: {style:google.maps.NavigationControlStyle.SMALL} 
            } 
            var maps = new google.maps.Map(document.getElementById("demo"), myOptions); 
            var markers = 
            new google.maps.Marker({position:lattlong, map:maps, title:"You are here!"}); 
        } 

        //Handling Error and Rejection
             function showErr(error) {
              switch(error.code){
              case error.PERMISSION_DENIED:
             alert("User denied the request for Geolocation API.");
              break;
             case error.POSITION_UNAVAILABLE:
             alert("USer location information is unavailable.");
            break;
            case error.TIMEOUT:
            alert("The request to get user location timed out.");
            break;
           case error.UNKNOWN_ERROR:
            alert("An unknown error occurred.");
            break;
           }
        }        </script> 
    </body> 
</html>

立即测试

要了解有关Google Maps JavaScript API的更多信息, 可以单击以下链接:

https://developers.google.com/maps/documentation/javascript/reference.

位置属性

Geolocation API的getCurrentPosition()方法返回用于检索用户位置信息的回调方法。此回调方法返回一个Position对象, 该对象包含所有位置信息并指定不同的属性。它总是返回纬度和经度属性, 但是下表描述了Position对象的其他一些属性。

物产 描述
coords.latitude 它以十进制数返回用户位置的纬度。
坐标经度 它以十进制数返回用户位置的经度。
coords.altitude 它返回海拔高度(以米为单位)(仅在可用时)。
坐标精度 它返回用户位置的准确性。
坐标高度精度 它返回用户位置的高度精度。 (如果可供使用的话)
coords.heading 它从北按顺时针方向返回标题。 (如果可供使用的话)
协调速度 它以米/秒为单位返回速度。 (如果可供使用的话)。
timestamp 它返回数据或响应时间。 (如果可供使用的话)。

观看当前位置

如果我们想知道用户在移动时的位置, 并希望在每个更改的位置上获得准确的位置, 则可以通过使用watchPosition()回调函数来实现。

此函数具有getCurrentPosition()包含的所有三个参数。

句法:

var id = navigator.geolocation.watchPosition(success[, error[, options]])

watchPosition()方法返回一个ID, 该ID可用于唯一标识用户的位置, 并且该ID也可以与clearWatch()方法一起使用以停止监视位置。

句法:

navigator.geolocation.clearWatch(id);

浏览器支持

API Chrome IE Firefox Opera Safari
Geolocation 5.0-49.0(http)50.0(https) 9.0 3.5 16.0 5.0
赞(0)
未经允许不得转载:srcmini » HTML5地理位置

评论 抢沙发

评论前必须登录!