HTML 突襲HTML5之Javascript API擴展2—地理信息服務及地理位置API學習 現在比較火的一類服務叫做基于位置的服務(location-based service, LBS),這一類服務就是企業利用某點(例如用戶所在的位置)坐標附近的區域提供服務的信息,比如常見的地圖相關服務。在HTML5中,加入了新的地理位置API用來確定和分享地理位置。 隱私申明 在與遠程Web服務器共享物理位置時,隱私是一個需要關注的問題。因此,地理位置API會要求用戶先提供權限,然后Webhtml' target='_blank'>應用程序才能訪問位置信息。首次訪問請求地理位置數據的網頁時,瀏覽器將顯示一個通知欄,提示提供對用戶位置的訪問權限。按照瀏覽器的提示,選擇相關的授權即可。 如果用戶未授予權限,則不會向 Web 應用程序提供位置信息。調用相關API不會觸發成功回調。 檢查瀏覽器的支持情況 地理位置API在主流的瀏覽器的最新版中都支持了,但是為了兼容老的瀏覽器,還是要檢查一下。如果地理位置 API 不可用,則 window.navigator.geolocation 將為 null,如下所示:
復制代碼代碼如下: function show_islocationenabled() { var str = "No, geolocation is not supported."; if (window.navigator.geolocation) { str = "Yes, geolocation is supported."; } alert( str ); }
復制代碼代碼如下: !DOCTYPE html html body p id="demo" Click the button to get your position: /p button Try It /button div id="mapholder" /div 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) { var latlon=position.coords.latitude+","+position.coords.longitude; var img_url="http://maps.googleapis.com/maps/api/staticmap?center=" + latlon + " zoom=9 size=400x300 sensor=false"; document.getElementById("mapholder").innerHTML=" img src='"+img_url+"' / } 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
復制代碼代碼如下: !DOCTYPE html html head title Geolocation API Example: Listening for Location Updates /title meta http-equiv="X-UA-Compatible" content="IE=9" / script type="text/javascript" function setText(val, e) { document.getElementById(e).value = val; } var nav = null; var watchID; function listenForPositionUpdates() { if (nav == null) { nav = window.navigator; } if (nav != null) { var geoloc = nav.geolocation; if (geoloc != null) { watchID = geoloc.watchPosition(successCallback); } else { alert("geolocation not supported"); } } else { alert("Navigator not found"); } } function clearWatch(watchID) { window.navigator.geolocation.clearWatch(watchID); } function successCallback(position) { setText(position.coords.latitude, "latitude"); setText(position.coords.longitude, "longitude"); } /script /head body label for="latitude" Latitude: /label input id="latitude" /