HTML5 的 Geolocation API 讓瀏覽器能取得使用者目前的地理座標,再搭配 Ajax 呼叫地圖服務的逆地理編碼介面,就能把「緯度、經度」這兩個數字翻譯成人看得懂的地址。本文寫一個小 demo,示範完整流程,同時示範兩種錯誤處理的做法。
動手之前必須把一件事說清楚:navigator.geolocation.getCurrentPosition() 一定會跳出瀏覽器的權限請求視窗,使用者按下「允許」之後,座標才會回傳。這個設計不是障礙,而是刻意的規範——嘗試繞過它、或在使用者不知情的情況下蒐集他人位置,在大多數國家的法律(個資保護相關法規)下都屬於違法行為,平台本身也不斷在封堵這類手法。
所以下面這個 demo 的定位對象,是正在 your 頁面上、按下允許的使用者本人。這也是這個 API 唯一應該被使用的方式。
畫面上分三塊:地理座標、百度地圖解析出的地址、Google 地圖解析出的地址。
<!DOCTYPE HTML> <html> <head> <meta charset="utf-"> <meta name="viewport" content="width=device-width, initial-scale=, maximum-scale="> <title>geolocation demo</title> <script type="text/javascript" src="https://libs.useso.com/js/jquery/../jquery.min.js"></script> <style type="text/css"> .demo{width:px; margin:px auto px auto} .geo{margin-top:px} .demo p{line-height:px; font-size:px} .demo p span,#baidu_geo,#google_geo{font-weight:bold} </style> </head> <body> <div id="main"> <div class="demo"> <p>地理坐標:<span id="latlon"></span></p> <div class="geo"> <p>百度地圖定位位置:</p> <p id="baidu_geo"></p> </div> <div class="geo"> <p>GOOGLE 地圖定位位置:</p> <p id="google_geo"></p> </div> </div> </div>
function getLocation(){ if (navigator.geolocation){ navigator.geolocation.getCurrentPosition(showPosition,showError); }else{ alert("瀏覽器不支援地理定位。"); } } function showError(error){ switch(error.code) { case error.PERMISSION_DENIED: alert("定位失敗,使用者拒絕請求地理定位"); break; case error.POSITION_UNAVAILABLE: alert("定位失敗,位置資訊不可用"); break; case error.TIMEOUT: alert("定位失敗,請求取得使用者位置逾時"); break; case error.UNKNOWN_ERROR: alert("定位失敗,定位系統失效"); break; } }
getCurrentPosition 的第二個參數是錯誤回呼,四種錯誤碼對應四種完全不同的處境:PERMISSION_DENIED 是使用者拒絕、POSITION_UNAVAILABLE 是訊號或網路問題、TIMEOUT 是逾時、UNKNOWN_ERROR 是其他。實務上建議再傳入第三個 options 物件(例如 {timeout: 10000, maximumAge: 60000})來控制等待時間與快取容忍度。
function showPosition(position){ $("#latlon").html("<br />緯度:"+position.coords.latitude +'<br />經度:'+ position.coords.longitude); var latlon = position.coords.latitude+','+position.coords.longitude; //百度 var url = "https://api.map.baidu.com/geocoder/v/?ak=Cbdaebdbbbabceb&callback=renderReverse&location="+latlon+"&output=json&pois="; $.ajax({ type: "GET", dataType: "jsonp", url: url, beforeSend: function(){ $("#baidu_geo").html('正在定位...'); }, success: function (json) { if(json.status==){ $("#baidu_geo").html(json.result.formatted_address); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { $("#baidu_geo").html(latlon+"地址位置獲取失敗"); } }); //google var url = 'https://maps.google.cn/maps/api/geocode/json?latlng='+latlon+'&language=CN'; $.ajax({ type: "GET", url: url, beforeSend: function(){ $("#google_geo").html('正在定位...'); }, success: function (json) { if(json.status=='OK'){ var results = json.results; $.each(results,function(index,array){ if(index==){ $("#google_geo").html(array['formatted_address']); } }); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { $("#google_geo").html(latlon+"地址位置獲取失敗"); } }); } getLocation();
HTTPS 是硬性要求。除了 localhost,現代瀏覽器只允許在 HTTPS 頁面呼叫 Geolocation。用 http 開的頁面會直接被拒,這一點在測試時經常被誤判成程式碼錯誤。
百度用了 JSONP,Google 沒有。這代表兩者的跨域策略不同:百度的 callback 參數讓它能以 script 標籤載入;而 Google 那個端點在跨域情況下需要改用支持 CORS 的版本,或請自己的後端代理一層。
API Key 不要寫在前端。範例中的 ak 明文放在 JavaScript 裡,任何人打開開發者工具就能拿走盜用。正式環境應在伺服器端配置金鑰並加上來源白名單(HTTP referer 限制),前端只呼叫自己的端點。
精度值要一起看。position.coords.accuracy 回傳的是以公尺為單位的誤差半徑。室內環境下這個值可能是數百公尺,此時顯示一個精確到門牌號的地址反而是誤導,UI 上應該適度模糊化處理。