地理定位太慢了!我做错了什么?

Fra*_*sco 25 javascript google-maps geolocation

这是我在测试页面中使用的简单代码:但是找到地址需要很长时间......为什么会这样?难道我做错了什么?

<script src="http://maps.google.com/maps?hl=it&amp;file=api&amp;v=2&amp;sensor=true&amp;key=*xxxxxx*" type="text/javascript"></script>
<script type="text/javascript">
    var map;
    var geocoder;

    function addAddressToMap(response) 
    {
      if (!response || response.Status.code != 200) 
      {
        alert("Sorry, we were unable to geocode that address");
      } 
      else 
      {
        place = response.Placemark[0];
        point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);

        document.getElementById('address').innerHTML = place.address;
      }
    }


    function searchGeolocation() 
    {
        if (navigator.geolocation) 
        {
            navigator.geolocation.getCurrentPosition(function(position) 
            {  
                geocoder = new GClientGeocoder();
                document.getElementById('latitude').innerHTML = position.coords.latitude;
                document.getElementById('longitude').innerHTML = position.coords.longitude;
                coordinates = position.coords.latitude+","+position.coords.longitude;
                geocoder.getLocations(coordinates, addAddressToMap);

            }); 
        }else
        {
            document.getElementById('latitude').innerHTML = "Unknown";
            document.getElementById('longitude').innerHTML = "Unknown";
            document.getElementById('address').innerHTML = "Unknown";
            alert("I'm sorry, but geolocation services are not supported by your browser.");    
        }
    }



</script>


<br/>
latitude = <div id="latitude">loading...</div>
<br/>
longitude = <div id="longitude">loading...</div>
<br/>
address = <div id="address">loading...</div>
<br/>


<script type="text/javascript">

    searchGeolocation();

</script>
Run Code Online (Sandbox Code Playgroud)

Chr*_*oot 11

嗯 - 它实际上在做地理定位!

要加快速度,请考虑提供额外的参数以利用缓存结果和超时.

  • 您可以在此处查看这些额外参数:https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions - 就我而言,这并没有什么区别。 (2认同)

Gal*_*len 8

我发现根据浏览器的不同,速度会有很大差异.我一直用铬测试我的地理定位,因为这几乎是即时的.Firefox很慢(很多时候它甚至不起作用),而Safari则排在第二位.希望他们能够及时修复它们的实现,因此它和chrome一样快


Hos*_*rad 5

我已经为此苦苦挣扎了几个小时,结果发现每个浏览器都有不同的结果,也就是代码无法完全控制的东西,但您可以通过将这些选项添加到函数调用来取得一些getlocation.getCurrentPosition进展:

enableHighAccuracy: false,
timeout: 5000,
maximumAge: Infinity
Run Code Online (Sandbox Code Playgroud)

您可以在此处详细了解每个选项的含义

要了解使用 Chrome 的基准测试:

enableHighAccuracy: true // ~3997ms
enableHighAccuracy: false // ~84ms
Run Code Online (Sandbox Code Playgroud)

注意:第一次调用这些函数时,仍然需要大约 3.9 秒。maximumAge可以通过使用或删除来减少每个后续调用enableHighAccuracy


ada*_*mse 0

您的几个呼叫可能需要几秒钟才能完成,例如navigator.geolocation.getCurrentPosition我在 Safari 中最多需要 5 秒(工作时)。