小強的HTML5移動開發之路(18)——HTML5地理定位

在前面的《小強的HTML5移動開發之路(2)——HTML5的新特性》中介紹了關於HTML5的地理定位功能,這一篇咱們來詳細瞭解一下怎麼使用該功能。javascript

HTML5 Geolocation API用於得到用戶的地理位置。html

鑑於該特性可能侵犯用戶的隱私,除非用戶贊成,不然用戶位置信息是不可用的,在使用該功能的時候瀏覽器會彈出提醒框。java

1、地理定位的幾種方式android

IP地址、GPS、Wifi、GSM/CDMAgit

2、地理位置獲取流程web

一、用戶打開須要獲取地理位置的web應用。api

二、應用向瀏覽器請求地理位置,瀏覽器彈出詢問,詢問用戶是否共享地理位置。瀏覽器

三、假設用戶容許,瀏覽器從設別查詢相關信息。服務器

四、瀏覽器將相關信息發送到一個信任的位置服務器,服務器返回具體的地理位置。函數

3、瀏覽器的支持

IE9.0+、FF3.5+、Safari5.0+、Chrome5.0+、Opera10.6+ 支持地理定位。

註釋:對於擁有 GPS 的設備,好比 iPhone(IPhone3.0+、Android2.0+),地理定位更加精確。

4、HTML5中地理位置定位的方法

GeolocationAPI存在於navigator對象中,只包含3個方法:

一、getCurrentPosition   //當前位置

二、watchPosition           //監視位置

三、clearWatch               //清除監視

5、地理定位方法getCurrentPosition()

<!DOCTYPE html>
<html>
<body>
	<p id="demo">點擊這個按鈕,得到您的座標:</p>
	<button onclick="getLocation()">試一下</button>
	<script>
		var x=document.getElementById("demo");
		function getLocation(){
		  if (navigator.geolocation){  //判斷是否支持地理定位
			  //若是支持,則運行getCurrentPosition()方法。
			  navigator.geolocation.getCurrentPosition(showPosition);
		  }else{
			  //若是不支持,則向用戶顯示一段消息
			  x.innerHTML="Geolocation is not supported by this browser.";
		  }
		}

		//獲取經緯度並顯示
		function showPosition(position){
		    x.innerHTML="Latitude: " + position.coords.latitude + 
		    "<br />Longitude: " + position.coords.longitude;	
		}
	</script>
</body>
</html>

getCurrentPosition(success,error,option)方法最多能夠有三個參數:

getCurrentPosition()方法第一個參數回調一個showPosition()函數並將位置信息傳遞給該函數,從該函數中獲取位置信息並顯示,

getCurrentPostion()方法第二個參數用於處理錯誤信息,它是獲取位置信息失敗的回調函數

getCurrentPostion()方法第三個參數是配置項,該參數是一個對象,影響了獲取位置的細節。

<!DOCTYPE html>
<html>
<body>
	<p id="demo">點擊這個按鈕,得到您的座標:</p>
	<button onclick="getLocation()">試一下</button>
	<script>
		var x=document.getElementById("demo");
		function getLocation(){
		  if (navigator.geolocation){  //判斷是否支持地理定位
			  //若是支持,則運行getCurrentPosition()方法。
			  navigator.geolocation.getCurrentPosition(showPosition,showError);
		  }else{
			  //若是不支持,則向用戶顯示一段消息
			  x.innerHTML="Geolocation is not supported by this browser.";
		  }
		}

		//獲取經緯度並顯示
		function showPosition(position){
		    x.innerHTML="Latitude: " + position.coords.latitude + 
		    "<br />Longitude: " + position.coords.longitude;	
		}

		//錯誤處理函數
		function showError(error){
		  switch(error.code)  //錯誤碼 
			{
			case error.PERMISSION_DENIED:  //用戶拒絕
			  x.innerHTML="User denied the request for Geolocation."
			  break;
			case error.POSITION_UNAVAILABLE:  //沒法提供定位服務
			  x.innerHTML="Location information is unavailable."
			  break;
			case error.TIMEOUT:  //鏈接超時
			  x.innerHTML="The request to get user location timed out."
			  break;
			case error.UNKNOWN_ERROR:  //未知錯誤
			  x.innerHTML="An unknown error occurred."
			  break;
			}
		 }
	</script>
</body>
</html>

6、在Google地圖中顯示結果

<!DOCTYPE html>
<html>
<body>
	<p id="demo">點擊這個按鈕,得到您的位置:</p>
	<button onclick="getLocation()">試一下</button>
	<div id="mapholder"></div>
		<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
		<script>
			var x=document.getElementById("demo");
				function getLocation(){
				   if (navigator.geolocation){
					 navigator.geolocation.getCurrentPosition(showPosition,showError);
					}else{
						x.innerHTML="Geolocation is not supported by this browser.";
					}
				}

				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!"});
				 }

				function showError(error){
					  switch(error.code){
						case error.PERMISSION_DENIED:
						  x.innerHTML="User denied the request for Geolocation."
						  break;
						case error.POSITION_UNAVAILABLE:
						  x.innerHTML="Location information is unavailable."
						  break;
						case error.TIMEOUT:
						  x.innerHTML="The request to get user location timed out."
						  break;
						case error.UNKNOWN_ERROR:
						  x.innerHTML="An unknown error occurred."
						  break;
						}
			    }
		</script>
</body>
</html>


7、在百度地圖中顯示結果

一、去百度開發者獲取地圖顯示密鑰

http://developer.baidu.com/map/jshome.htm


<!DOCTYPE html>
<html>
<body>
	<p id="demo">點擊這個按鈕,得到您的位置:</p>
	<button onclick="getLocation()">試一下</button>
	<div id="mapholder" style="width:600px;height:500px;"></div>
		<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=你本身的密鑰"></script>
		<script>
			var x=document.getElementById("demo");
				function getLocation(){
				   if (navigator.geolocation){
					 navigator.geolocation.getCurrentPosition(showPosition,showError);
					}else{
						x.innerHTML="Geolocation is not supported by this browser.";
					}
				}

				function showPosition(position){
					//alert(position.coords.longitude + " ___ " + position.coords.latitude);
					 
					// 百度地圖API功能
					var map = new BMap.Map("mapholder");            // 建立Map實例
					var point = new BMap.Point(position.coords.longitude, position.coords.latitude);    // 建立點座標
					map.centerAndZoom(point,15);                     // 初始化地圖,設置中心點座標和地圖級別。
					map.enableScrollWheelZoom(); 
				 }

				function showError(error){
					  switch(error.code){
						case error.PERMISSION_DENIED:
						  x.innerHTML="User denied the request for Geolocation."
						  break;
						case error.POSITION_UNAVAILABLE:
						  x.innerHTML="Location information is unavailable."
						  break;
						case error.TIMEOUT:
						  x.innerHTML="The request to get user location timed out."
						  break;
						case error.UNKNOWN_ERROR:
						  x.innerHTML="An unknown error occurred."
						  break;
						}
			    }
		</script>
</body>
</html>

注意:若是拷貝上面代碼,請將「你本身的密鑰」替換爲在百度開發者中心申請的密鑰


能夠看到Google Map 和百度地圖的定位參考不一樣,因此用ip定位偏差很大。

8、getCurrentPosition()方法—返回數據

若成功,則 getCurrentPosition() 方法返回對象。始終會返回 latitude、longitude 以及 accuracy 屬性。若是可用,則會返回其餘下面的屬性。

屬性 描述
coords.latitude 十進制數的緯度
coords.longitude 十進制數的經度
coords.accuracy 位置精度
coords.altitude 海拔,海平面以上以米計
coords.altitudeAccuracy 位置的海拔精度
coords.heading 方向,從正北開始以度計
coords.speed 速度,以米/每秒計
timestamp 響應的日期/時間

還能夠得到地理位置(只有firefox支持)

p.address.country   國家

p.address.region    省份

p.address.city          城市

9、監視位置(移動設備中)

watchPosition() - 返回用戶的當前位置,並繼續返回用戶移動時的更新位置(就像汽車上的 GPS)。

clearWatch() - 中止 watchPosition() 方法

下面的例子展現 watchPosition() 方法

watchPosition像一個追蹤器與clearWatch成對。

watchPositionclearWatch有點像setIntervalclearInterval的工做方式。

varwatchPositionId =navigator.geolocation.watchPosition(success_callback,error_callback,options);

navigator.geolocation.clearWatch(watchPositionId );

<!DOCTYPE html>
<html>
<body>
<p id="demo">點擊這個按鈕,得到您的座標:</p>
<button onclick="getLocation()">試一下</button>
<script>
var x=document.getElementById("demo");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.watchPosition(showPosition);
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }
function showPosition(position)
  {
  x.innerHTML="Latitude: " + position.coords.latitude + 
  "<br />Longitude: " + position.coords.longitude;	
  }
</script>
</body>
</html>


Java學習交流羣142979499 JAVA技術交流羣
Android學習交流羣311273384 android學習交流羣
相關文章
相關標籤/搜索