【问题标题】:Calculate distance between current location and and a different location using Google Maps API V3使用 Google Maps API V3 计算当前位置与不同位置之间的距离
【发布时间】:2013-04-13 05:32:20
【问题描述】:

我正在尝试计算我所在位置与其他位置之间的距离,但我得到的只是 NaN。我很确定我将代码放在脚本中的错误位置。有人可以帮我解决这个问题吗?

<!DOCTYPE html>
<html>
<head>
    <script src="http://maps.google.com/maps/api/js?sensor=false&v=3&libraries=geometry"></script>
</head>
<body>
    <p id="demo"></p>
    <button onclick="getLocation()" id="demo">get current location</button>
    <button onclick="console.log(distance)">get ditance from current location to other location</button>

    <script>
        var lat;
        var longt;
        var latLngA = new google.maps.LatLng(lat, longt);
        var latLngB = new google.maps.LatLng(40.778721618334295, -73.96648406982422);
        var distance = google.maps.geometry.spherical.computeDistanceBetween(latLngA, latLngB);

        var x=document.getElementById("demo");

        function getLocation(){
            if (navigator.geolocation){
                navigator.geolocation.getCurrentPosition(showPosition);
            }
            else{
                x.innerHTML="Geolocation is not supported by this browser.";}
            }

        function showPosition(position){
            lat = position.coords.latitude;
            longt = position.coords.longitude;
            x.innerHTML="Latitude: " + lat + "<br>Longitude: " + longt; 
        }
    </script>
</body>
</html>

【问题讨论】:

  • latLngA 是一个位置吗?坐标设置好了吗?
  • 是的,就是当前位置。
  • 它的NaN 因为你的latLngA = NaN
  • LatLng 构造函数文档LatLng(lat:number, lng:number, noWrap?:boolean)

标签: javascript html google-maps-api-3 geolocation


【解决方案1】:

使用libraries=geometry的简化脚本

function getLocation() {
  navigator.geolocation.getCurrentPosition(
            function(position) {
                var latLngA = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
                var latLngB = new google.maps.LatLng(40.778721618334295, -73.96648406982422);
                var distance = google.maps.geometry.spherical.computeDistanceBetween(latLngA, latLngB);
                alert(distance);//In metres
            },
            function() {
                alert("geolocation not supported!!");
            }
    );
}

【讨论】:

  • 完美运行!但是有一个问题:function(position) 是否必须声明为function(position)?这是 API 的语法吗?
  • 只是为了澄清一些观点。 A) 距离以米为单位。 B) google.maps.geometry 库默认不加载,因此您必须在加载 Google Maps API 时将“&libraries=geometry”添加到 URL。请参阅docs 了解更多信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-04
  • 1970-01-01
  • 2011-12-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-20
相关资源
最近更新 更多