HTML5 地理位置

HTML5 地理定位功能用於查詢站點訪問者的位置。

什麼是地理位置

通過 HTML5 地理定位功能,你可以找到網站訪問者當前位置的地理座標(緯度和經度數)。此功能有助於為網站訪問者提供更好的瀏覽體驗。例如,你可以返回物理上靠近使用者位置的搜尋結果。

尋找訪客的座標

使用 HTML5 地理定位 API 獲取站點訪問者的位置資訊非常簡單。它利用被包裝到了這三種方法 navigator.geolocation 的物件- getCurrentPosition()watchPosition()clearWatch()

以下是顯示當前位置的地理位置的簡單示例。但是,首先你需要同意讓瀏覽器告訴 Web 伺服器你的位置。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML5 Geolocation</title>
<script type="text/javascript">
    function showPosition(){
        if(navigator.geolocation){
            navigator.geolocation.getCurrentPosition(function(position){
                var positionInfo = "Your current position is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " + position.coords.longitude + ")";
                document.getElementById("result").innerHTML = positionInfo;
            });
        } else{
            alert("Sorry, your browser does not support HTML5 geolocation.");
        }
    }
</script>
</head>
<body>
    <div id="result">
        <!--Position information will be inserted here-->
    </div>
    <button type="button" onclick="showPosition();">Show Position</button>
</body>
</html>

注意: 除非訪問者明確許可,否則瀏覽器不會與網頁共享訪問者位置。地理位置標準使得獲得使用者對每個想要位置資料的網站的許可權成為官方規則。

處理錯誤和拒絕

可能存在使用者不想與你共享其位置資料的情況。為了處理這種情況,你可以在呼叫 getCurrentLocation() 時提供兩個函式。如果你的地理位置嘗試成功,則呼叫第一個函式;如果地理位置嘗試以失敗結束,則呼叫第二個函式。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML5 Geolocation</title>
<script type="text/javascript">
    // Set up global variable
    var result;
    
    function showPosition(){
        // Store the element where the page displays the result
        result = document.getElementById("result");
        
        // If geolocation is available, try to get the visitor's position
        if(navigator.geolocation){
            navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
            result.innerHTML = "Getting the position information...";
        } else{
            alert("Sorry, your browser does not support HTML5 geolocation.");
        }
    };
    
    // Define callback function for successful attempt
    function successCallback(position){
        result.innerHTML = "Your current position is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " + position.coords.longitude + ")";
    }
    
    // Define callback function for failed attempt
    function errorCallback(error){
        if(error.code == 1){
            result.innerHTML = "You've decided not to share your position, but it's OK. We won't ask you again.";
        } else if(error.code == 2){
            result.innerHTML = "The network is down or the positioning service can't be reached.";
        } else if(error.code == 3){
            result.innerHTML = "The attempt timed out before it could get the location data.";
        } else{
            result.innerHTML = "Geolocation failed due to unknown error.";
        }
    }
</script>
</head>
<body>
    
        <!--Position information will be inserted here-->
    
    <button type="button" onclick="showPosition();">Show Position</button>
</body>
</html>

在 Google 地圖上顯示位置

你可以使用地理位置資料執行非常有趣的操作,例如在 Google 地圖上顯示使用者位置。以下示例將根據通過 HTML5 地理位置功能檢索的緯度和經度資料顯示你在 Google 地圖上的當前位置。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML5 Geolocation</title>
<script type="text/javascript">
    function showPosition(){
        navigator.geolocation.getCurrentPosition(showMap);
    }
    
    function showMap(position){
        // Get location data
        var latlong = position.coords.latitude + "," + position.coords.longitude;
        
        // Set Google map source url
        var mapLink = "https://maps.googleapis.com/maps/api/staticmap?center="+latlong+"&zoom=16&size=400x300&output=embed";
        
        // Create and insert Google map
        document.getElementById("embedMap").innerHTML = "<img alt='Map Holder' src='"+ mapLink +"'>";
    }
</script>
</head>
<body>
    <button type="button" onclick="showPosition();">Show My Position on Google Map</button>
    <div id="embedMap">
        <!--Google map will be embedded here-->
    </div>
</body>
</html>

上面的示例將使用靜態影象顯示 Google 地圖上的位置。但是,你還可以建立具有拖動,放大/縮小功能以及你在現實生活中遇到的其他功能的互動式 Google 地圖。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML5 Geolocation</title>
<script src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function showPosition(){
    if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(showMap, showError);
    } else{
        alert("Sorry, your browser does not support HTML5 geolocation.");
    }
}
 
// Define callback function for successful attempt
function showMap(position){
    // Get location data
    lat = position.coords.latitude;
    long = position.coords.longitude;
    var latlong = new google.maps.LatLng(lat, long);
    
    var myOptions = {
        center: latlong,
        zoom: 16,
        mapTypeControl: true,
        navigationControlOptions: {style:google.maps.NavigationControlStyle.SMALL}
    }
    
    var map = new google.maps.Map(document.getElementById("embedMap"), myOptions);
    var marker = new google.maps.Marker({position:latlong, map:map, title:"You are here!"});
}
 
// Define callback function for failed attempt
function showError(error){
    if(error.code == 1){
        result.innerHTML = "You've decided not to share your position, but it's OK. We won't ask you again.";
    } else if(error.code == 2){
        result.innerHTML = "The network is down or the positioning service can't be reached.";
    } else if(error.code == 3){
        result.innerHTML = "The attempt timed out before it could get the location data.";
    } else{
        result.innerHTML = "Geolocation failed due to unknown error.";
    }
}
</script>
</head>
<body>
    <button type="button" onclick="showPosition();">Show My Position on Google Map</button>
    <div id="embedMap" style="width: 400px; height: 300px;">
        <!--Google map will be embedded here-->
    </div>
</body>
</html>

請檢視以下網址,詳細瞭解 Google Maps Javascript API:https://developers.google.com/maps/documentation/javascript/reference

監控訪客的運動

到目前為止我們使用的所有示例都依賴於該 getCurrentPosition() 方法。但是,地理定位物件具有另一種方法 watchPosition() ,允許你通過在位置更改時返回更新的位置來跟蹤訪問者的移動。

watchPosition() 具有同 getCurrentPosition() 相同的輸入引數。但是, watchPosition() 可能會多次觸發成功功能 - 當它第一次獲得位置時,並且每次檢測到新位置時都會觸發。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML5 Geolocation</title>
<script type="text/javascript">
    // Set global variable
    var watchID;
    function showPosition(){
        if(navigator.geolocation){
            watchID = navigator.geolocation.watchPosition(successCallback);
        } else{
            alert("Sorry, your browser does not support HTML5 geolocation.");
        }
    }
    function successCallback(position){
        toggleWatchBtn.innerHTML = "Stop Watching";
        
        // Check position has been changed or not before doing anything
        if(prevLat != position.coords.latitude || prevLong != position.coords.longitude){
            
            // Set previous location
            var prevLat = position.coords.latitude;
            var prevLong = position.coords.longitude;
            
            // Get current position
            var positionInfo = "Your current position is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " + position.coords.longitude + ")";
            document.getElementById("result").innerHTML = positionInfo;
            
        }
        
    }
    function startWatch(){
        var result = document.getElementById("result");
        
        var toggleWatchBtn = document.getElementById("toggleWatchBtn");
        
        toggleWatchBtn.onclick = function(){
            if(watchID){
                toggleWatchBtn.innerHTML = "Start Watching";
                navigator.geolocation.clearWatch(watchID);
                watchID = false;
            }
            else{
                toggleWatchBtn.innerHTML = "Aquiring Geo Location...";
                showPosition();
            }
        }
    }
    
    // Initialise the whole system (above)
    window.onload = startWatch;
</script>
</head>
<body>
    <button type="button" id="toggleWatchBtn">Start Watching</button>
    <div id="result">
        <!--Position information will be inserted here-->
    </div>   
</body>
</html>