地理位置定位(Geolocation) - Web APIs | MDN

文章推薦指數: 80 %
投票人數:10人

Web Apps 若需要使用者的位置,可透過Geolocation API 取得相關資訊。

而基於隱私權的考量,這些Web Apps 均必須取得使用者的許可之後,才能發佈位置 ... SkiptomaincontentSkiptosearchSkiptoselectlanguage給開發者的網頁技術文件WebAPIs地理位置定位(Geolocation)ArticleActions正體中文(繁體)ThispagewastranslatedfromEnglishbythecommunity.LearnmoreandjointheMDNWebDocscommunity.地理位置定位(Geolocation)物件敘述位置處理錯誤地理位置定位實際範例請求權限規範瀏覽器相容性Gecko註記另請參閱地理位置定位(Geolocation)物件敘述位置處理錯誤地理位置定位實際範例請求權限規範瀏覽器相容性Gecko註記另請參閱地理位置定位(Geolocation)WebApps若需要使用者的位置,可透過GeolocationAPI取得相關資訊。

而基於隱私權的考量,這些WebApps均必須取得使用者的許可之後,才能發佈位置資訊。

地理位置定位(Geolocation)物件GeolocationAPI,是透過navigator.geolocation(en-US)物件所發佈。

若該物件可用,即可進行地理位置定位服務。

因此可先測試地理位置定位是否存在: if("geolocation"innavigator){ /*geolocationisavailable*/ }else{ /*geolocationISNOTavailable*/ } 備註:在Firefox24之後的版本,即使停用此API,navigator中的「geolocation」也同樣回傳true。

此問題已根據規格而於`Firefox25中修正(bug884921)。

取得目前位置 若要取得使用者目前的位置,可呼叫getCurrentPosition()函式。

如此將啟動非同步化的請求,以偵測使用者的位置,並將查詢定位硬體而取得最新資訊。

一旦決定位置,隨即執行特定的回呼常式(Callbackroutine)。

若發生錯誤,則可選擇是否提供第二次回呼。

第三項參數為選項介面(亦可選擇是否使用之),可設定位置回傳的的最長時間,與請求的等待時間。

若不論定位精確度而想儘快固定單一位置,則可使用getCurrentPosition()。

以具備GPS的裝置為例,往往需耗時1分鐘或更長的時間而固定GPS資訊。

也因此,getCurrentPosition()可能取得較低精確度的資料(IP位置或WiFi)而隨即開始作業。

備註:依預設值,getCurrentPosition()(en-US)將儘快回傳較低精確度的結果。

若不論精確度而只要儘快獲得答案,則可使用getCurrentPosition()(en-US)。

舉例來說,搭載GPS的裝置可能需要一段時間才能取得GPS定位資訊,所以可能將低精確度的資料(IP位置或Wifi)回傳至getCurrentPosition()(en-US)。

navigator.geolocation.getCurrentPosition(function(position){ do_something(position.coords.latitude,position.coords.longitude); }); 一旦取得定位位置之後,上列範例隨即將執行do_something()函式。

觀看目前位置如果定位資料改變(可能是裝置移動,或取得更精確的地理位置資訊),則可設定1組回呼函式,使其隨著更新過的定位資訊而呼叫之。

而這個動作可透過watchPosition()函式完成。

watchPosition()(en-US)所具備的輸入參數與getCurrentPosition()相同。

回呼函式將呼叫數次,讓瀏覽器可於使用者移動期間更新位置,或可根據目前所使用的不同定位技術,提供更精確的定位資訊。

若一直未回傳有效結果,則錯誤回呼(ErrorCallback)函式僅將呼叫1次。

另請注意,錯誤回呼函式僅限於getCurrentPosition(),因此為選填。

備註:不需啟動getCurrentPosition()(en-US)呼叫,亦可使用watchPosition()(en-US)。

varwatchID=navigator.geolocation.watchPosition(function(position){ do_something(position.coords.latitude,position.coords.longitude); } ); watchPosition()函式將回傳1組ID編號,專用以識別必要的定位監看員(Watcher)。

而此數值若搭配clearWatch()函式,即可停止觀看使用者的位置。

navigator.geolocation.clearWatch(watchID); 微調回應getCurrentPosition()(en-US)與watchPosition()(en-US)均可容納1組成功回呼、1組錯誤回呼(選填)、1組PositionOptions物件(選填)。

對watchPosition(en-US)的呼叫應類似如下: functiongeo_success(position){ do_something(position.coords.latitude,position.coords.longitude); } functiongeo_error(){ alert("Sorry,nopositionavailable."); } vargeo_options={ enableHighAccuracy:true, maximumAge:30000, timeout:27000 }; varwpid=navigator.geolocation.watchPosition(geo_success,geo_error,geo_options); 現成的watchPositionDemo:http://www.thedotproduct.org/experiments/geo/敘述位置以Position物件參照Coordinates物件,即可敘述使用者的位置。

處理錯誤在呼叫getCurrentPosition()或watchPosition()時,若獲得錯誤回呼函式,則錯誤回呼函式的第一組參數將為PositionError物件: functionerrorCallback(error){alert('ERROR('+error.code+'):'+error.message);}; 地理位置定位實際範例HTML內容

Showmylocation

JavaScript內容functiongeoFindMe(){ varoutput=document.getElementById("out"); if(!navigator.geolocation){ output.innerHTML="

Geolocationisnotsupportedbyyourbrowser

"; return; } functionsuccess(position){ varlatitude=position.coords.latitude; varlongitude=position.coords.longitude; output.innerHTML='

Latitudeis'+latitude+'°
Longitudeis'+longitude+'°

'; varimg=newImage(); img.src="http://maps.googleapis.com/maps/api/staticmap?center="+latitude+","+longitude+"&zoom=13&size=300x300&sensor=false"; output.appendChild(img); }; functionerror(){ output.innerHTML="Unabletoretrieveyourlocation"; }; output.innerHTML="

Locating…

"; navigator.geolocation.getCurrentPosition(success,error); } 現場測試結果若無法顯示,可至本文右上角「Language」切換回英文原文觀看。

請求權限addons.mozilla.org上所提供的任何附加元件,只要使用地理位置定位資料,均必須明確取得許可才能繼續作業。

下列函式詢問許可的方法,則類似網頁詢問許可的自動提示方法,但更為簡單。

若為可套用的狀態,則使用者的回應將儲存於pref參數所指定的偏好中。

於callback參數中所提供的函式,將透過1組代表使用者反應的布林值而呼叫之。

若使用者的回應為true,則附加元件才會存取地理位置定位資料。

functionprompt(window,pref,message,callback){ letbranch=Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefBranch); if(branch.getPrefType(pref)===branch.PREF_STRING){ switch(branch.getCharPref(pref)){ case"always": returncallback(true); case"never": returncallback(false); } } letdone=false; functionremember(value,result){ returnfunction(){ done=true; branch.setCharPref(pref,value); callback(result); } } letself=window.PopupNotifications.show( window.gBrowser.selectedBrowser, "geolocation", message, "geo-notification-icon", { label:"ShareLocation", accessKey:"S", callback:function(notification){ done=true; callback(true); } },[ { label:"AlwaysShare", accessKey:"A", callback:remember("always",true) }, { label:"NeverShare", accessKey:"N", callback:remember("never",false) } ],{ eventCallback:function(event){ if(event==="dismissed"){ if(!done)callback(false); done=true; window.PopupNotifications.remove(self); } }, persistWhileVisible:true }); } prompt(window, "extensions.foo-addon.allowGeolocation", "FooAdd-onwantstoknowyourlocation.", functioncallback(allowed){alert(allowed);}); 規範SpecificationGeolocationAPI#geolocation_interface瀏覽器相容性BCDtablesonlyloadinthebrowserGecko註記Firefox可透過Google的定位服務(GoogleLocationServices,GLS),根據使用者的WiFi資訊而找出使用者的位置。

與Google之間所交換的資料,包含WiFi存取點(AccessPoint)資料、Accesstoken(類似2個禮拜的cookie)、使用者的IP位址。

若需更多資訊,可參閱Mozilla的隱私權政策與Google的隱私權政策。

其內將詳述資料的使用方式。

Firefox3.6(Gecko1.9.2)新支援了GPSD(GPSdaemon)服務,適合Linux的地理位置定位。

另請參閱 navigator.geolocation(en-US) w3.org的GeolocationAPI GeolocationAPI相關Demos Foundaproblemwiththispage?EditonGitHubSourceonGitHubReportaproblemwiththiscontentonGitHubWanttofixtheproblemyourself?SeeourContributionguide.Lastmodified:2022年9月20日,byMDNcontributors


請為這篇文章評分?