如何使用 HTML5 地理位置資訊查詢位置?
HTML5 地理位置資訊 API 允許你與你喜愛的網站共享你的位置。JavaScript 能夠獲取你的緯度和經度併發送到後端 Web 服務,並執行諸如查詢當地企業或在地圖上顯示你的位置等時髦的與位置相關的操作。
地理位置資訊 API 與全域性導航器物件(即地理位置物件)的新屬性一起使用。
getCurrentPosition 方法會檢索裝置當前的地理位置。位置表示為一組地理座標以及有關航向和速度的資訊。位置資訊會返回到一個位置物件。
示例
你可以嘗試執行下列程式碼來查詢當前位置
<!DOCTYPE HTML> <html> <head> <script type = "text/javascript"> function showLocation(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; alert("Latitude : " + latitude + " Longitude: " + longitude); } function errorHandler(err) { if(err.code == 1) { alert("Error: Access is denied!"); } else if( err.code == 2) { alert("Error: Position is unavailable!"); } } function getLocation(){ if(navigator.geolocation){ // timeout at 60000 milliseconds (60 seconds) var options = {timeout:60000}; navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options); } else { alert("Sorry, browser does not support geolocation!"); } } </script> </head> <body> <form> <input type = "button" onclick = "getLocation();" value = "Get Location"/> </form> </body> </html>
廣告