简体   繁体   English

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

[英]Calculate distance between current location and and a different location using Google Maps API V3

I'm trying to calculate the distance between my location and a different location, but all I get is NaN. 我正在尝试计算我的位置和不同位置之间的距离,但我得到的只是NaN。 I'm pretty sure I placed the code in the wrong place in the script. 我很确定我将代码放在脚本中的错误位置。 Can somebody help me figuring this issue? 有人可以帮我解决这个问题吗?

<!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>

Simplified script using libraries=geometry 使用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!!");
            }
    );
}

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

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