日期:2014-05-17  浏览次数:20620 次

HTML5中使用geolocation API获取用户的位置

下面的例子展示了如何在在HTML5中通过geolocation API 获取用户的位置(经度,纬度)。

?

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        function body_onLoad() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(geo_onSuccess, geo_onError);
            } else {
                geo_onError();
            }
        }
 
        function geo_onSuccess(pos) {
            document.getElementById("timestamp").innerHTML = new Date().toLocaleString();
            document.getElementById("accuracySpan").innerHTML = pos.coords.accuracy;
            document.getElementById("altitudeSpan").innerHTML = pos.coords.aktitude;
            document.getElementById("altitudeAccuracySpan").innerHTML = pos.coords.altitudeAccuracy;
            document.getElementById("headingSpan").innerHTML = pos.coords.heading;
            document.getElementById("latitudeSpan").innerHTML = pos.coords.latitude;
            document.getElementById("longitudeSpan").innerHTML = pos.coords.longitude;
            document.getElementById("speedSpan").innerHTML = pos.coords.speed;
        }
 
        function geo_onError() {
            alert("Unable to get latitude/longitude, or browser does not support geolocation API.");
        }
    </script>
</head>
<body onload="body_onLoad();">
 
    <h1>navigator.geolocation</h1>
    <table>
    <tr>
        <th>accuracy:</th>
        <td><span id="accuracySpan"></span></td>
    </tr>
    <tr>
        <th>altitude:</th>
        <td><span id="altitudeSpan"></span></td>
    </tr>
    <tr>
        <th>altitudeAccuracy:</th>
        <td><span id="altitudeAccuracySpan"></span></td>
    </tr>
    <tr>
        <th>heading:</th>
        <td><span id="headingSpan"></span></td>
    </tr>
    <tr>
        <th>latitude:</th>
        <td><span id="latitudeSpan"></span></td>
    </tr>
    <tr>
        <th>longitude:</th>
        <td><span id="longitudeSpan"></span></td>
    </tr>
    <tr>
        <th>speed:</th>
        <td><span id="speedSpan"></span></td>
    </tr>
    </table>
    <p id="timestamp"/>
 
</body>
</html>
?

源码下载:

?

determining-the-users-location.zip

?