HTML5 提供了 Geolocation API,它允許 Web 應用程式存取使用者的地理位置。地理定位 API 是基於 W3C 地理定位 API 規格。

以下是如何在 HTML5 中使用 Geolocation API 的基本範例:

  1. 檢查地理定位支援:在使用地理定位 API 之前,最好檢查瀏覽器是否支援它。

    html
    <script> if ("geolocation" in navigator) { // Geolocation is supported // Your code for using the Geolocation API goes here } else { // Geolocation is not supported alert("Geolocation is not supported in this browser"); } </script>
  2. 取得使用者位置:如果支援地理定位,可以使用方法navigator.geolocation.getCurrentPosition()取得使用者目前位置。

    html
    <script> if ("geolocation" in navigator) { navigator.geolocation.getCurrentPosition(successCallback, errorCallback); } else { alert("Geolocation is not supported in this browser"); } function successCallback(position) { // The user's location is available in the 'position' object var latitude = position.coords.latitude; var longitude = position.coords.longitude; // Do something with the latitude and longitude console.log("Latitude: " + latitude); console.log("Longitude: " + longitude); } function errorCallback(error) { // Handle errors console.error("Error getting geolocation: " + error.message); } </script>

    成功檢索位置時呼叫successCallback函數,如果發生錯誤,則呼叫errorCallback函數。

  3. 處理錯誤: errorCallback函數可以處理各種錯誤,錯誤訊息可在error參數中取得。常見錯誤包括權限被拒絕、位置不可用和逾時。

    javascript
    function errorCallback(error) { switch (error.code) { case error.PERMISSION_DENIED: console.error("User denied the request for Geolocation."); break; case error.POSITION_UNAVAILABLE: console.error("Location information is unavailable."); break; case error.TIMEOUT: console.error("The request to get user location timed out."); break; default: console.error("An unknown error occurred."); break; } }

請記住,某些用戶可能選擇不共享他們的位置,因此您的應用程式應該準備好處理位置不可用的情況。

請注意,存取使用者位置通常需要安全上下文(即頁面應透過 HTTPS 提供服務)。如果您的網站透過 HTTP 提供服務,瀏覽器可能不允許存取 Geolocation API。