DIV CSS 佈局教程網

用 js + HTML5 取得使用者地理位置並在地圖上顯示
編輯:關於JavaScript     

本文要分享的是用 JavaScript 搭配 HTML5 取得使用者地理位置資訊,並在 Google 地圖上顯示的方法,完整實作程式碼如下,供大家參考動手試做。

 <!DOCTYPE html> <html> <body> <p id="demo">Click the button to get your position:</p> <button onclick="getLocation()">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="https://maps.googleapis.com/maps/api/staticmap?center=" +latlon+"&zoom=14&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> 

做法是透過 navigator.geolocation.getCurrentPosition 取得座標,成功時在 showPosition 中組出靜態地圖的圖片網址並插入頁面;失敗時則由 showError 依錯誤碼(拒絕、無法取得、逾時、未知錯誤)給出對應提示。希望本文對你的 Web 程式設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved