繁体   English   中英

Javascript getCurrentPosition() function 在本地主机上给了我不正确的纬度和经度值

[英]Javascript getCurrentPosition() function giving me incorrect latitude and longitude values on localhost

Here is my code...

<!DOCTYPE html>
<html>
    <head>
        <title>Geeting User Location</title>
    </head>
    <body>
        <button onclick="getLocation()">Click here to get your address</button><br><br>
        <label>Address: </label>
        <textarea cols="100" rows="5" id="demo"></textarea>
    </body>
</html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>
    var x = document.getElementById("demo");

    function getLocation()
    {
        if (navigator.geolocation)
        {
            navigator.geolocation.getCurrentPosition(function(position){showPosition(position)}, null, {
                maximumAge: 75000,
                timeout: 30000,
                enableHighAccuracy: true,
            });
        }
        else
        {
            x.innerHTML = "Geolocation is not supported by this browser.";
        }
    }

    function showPosition(position)
    {
        var locApi = "https://maps.googleapis.com/maps/api/geocode/json?latlng="+position.coords.latitude+","+position.coords.longitude+"&key=MY_API_KEY_HERE";

        $.ajax({
          url: locApi,
          dataType: 'json',
          type: 'GET',
          success: function(data) {
            console.log(data);
            var address = data.city;
            address += data.region;
            address += data.country;
            $("#demo").append(JSON.stringify(address));
          },
          error: function() {
             $('#demo').html('<p>An error has occurred</p>');
          },
       });
    }
</script>

当用户单击按钮时,我想通过纬度和经度值以及 append 将城市、地区、国家名称获取到文本区域。 我想知道我错在哪里。 地理位置是否没有在本地主机上提供正确的纬度和经度值。

请参阅https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPositionhttps://www.sitepoint.com/html5-geolocation/

如果您使用的设备没有高精度 GPS ,则可能是基于广泛假设的位置,例如您的 IP 地址或您的 ISP(互联网服务提供商)所在的位置。

您还应该获得该位置的Accuracy测量值,以便估计您获得的信息的准确度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM