JavaScript 取得使用者位置 Geolocation

現在要取得使用者的位置已經非常簡單了,會自動請求權限,使用者點擊後就會取得經緯度座標了:
    
// 檢查瀏覽器是否支援 Geolocation API
if ("geolocation" in navigator) {
    // 瀏覽器支援 Geolocation API
    navigator.geolocation.getCurrentPosition(function(position) {
        // 取得經緯度成功
        console.log("Latitude (緯度):", position.coords.latitude);
        console.log("Longitude (經度):", position.coords.longitude);
    }, function(error) {
        // 發生錯誤(可能是使用者拒絕)
        console.error("Error Code (錯誤代碼) = " + error.code + " - " + error.message);
    });
} else {
    // 瀏覽器不支援 Geolocation API
    console.log("Geolocation is not supported by this browser.");
}

    



參考資料:
mdn - Geolocation API

留言