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>