在HTML5中使用地理位置时不显示位置

Location Not Displayed When Using Geo location in HTML5

本文关键字:显示 位置 地理位置 HTML5      更新时间:2023-09-26

我正在开发一个Phone Gap应用程序。在这个应用程序中,我想显示当前用户的位置。为此,我使用了HTML5地理定位。当我点击Get Location按钮时它不会显示位置。它也不会显示错误。按下获取位置按钮后,它只是显示按钮在选定状态。

<!DOCTYPE html>
<html>
<body>
    <button onclick="getLocation()">Get Location</button>
    <script>
        var x = document.getElementById("demo");
        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showPosition, showError);
            }
            else { x.innerHTML = "Geolocation is not supported by this browser."; }
        }
        function showPosition(position) {
            x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
        }
        function showError(error) {
            switch (error.code) {
                case error.PERMISSION_DENIED:
                    x.innerHTML = "User denied the request for Geolocation."
                    break;
                case error.POSITION_UNAVAILABLE:
                    x.innerHTML = "Location information is unavailable."
                    break;
                case error.TIMEOUT:
                    x.innerHTML = "The request to get user location timed out."
                    break;
                case error.UNKNOWN_ERROR:
                    x.innerHTML = "An unknown error occurred."
                    break;
            }
        }
    </script>
</body>
</html>

您正在引用一个不存在的元素。在html正文中添加一个div, id="demo",如下所示:

<div id="demo"></div>

可以在jsfiddle上看到:http://jsfiddle.net/wU6AE/