使用Google Maps API V3计算当前位置与其他位置之间的距离

3

我想计算我所在位置和另一个位置之间的距离,但是结果仅显示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是一个位置吗?它的坐标已经设置了吗? - Jensd
是的,这就是当前位置。 - user2275870
它是 NaN,因为你的 latLngA = NaN - David Chase
The LatLng构造函数文档 LatLng(lat:number, lng:number, noWrap?:boolean) - david strachan
1个回答

7

使用 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的语法吗? - user2275870
1
只是澄清一些要点。A)距离以米为单位。B)默认情况下未加载google.maps.geometry库,因此在加载Google Maps API时必须将“&libraries = geometry”添加到URL中。有关更多信息,请参见[文档](https://developers.google.com/maps/documentation/javascript/libraries)。 - kzfabi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接