查找从调用地理编码两次创建的两个latlng对象的距离

时间:2015-03-07 17:34:00

标签: javascript google-maps-api-3

我的代码中创建了两个latlng对象,由于异步请求,在调用它们之后,这两个值中的任何一个都不可用。

如何找到这两点之间的距离?

我找到了寻找距离的代码,只是无法获得那些latlng值!

以下是代码:

function onselectchange(){
var address = document.getElementById("start").value;

var address2 = document.getElementById("end").value;

var startLat, startLong, endLat, endLong;
var Firstlatlng , Secondlatlng;
geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {

  startLat = results[0].geometry.location.lat();
  startLong = results[0].geometry.location.lng();

  Firstlatlng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng());
    //alert("Inside:"+startLat);



  } 

  else {
    alert("Geocode was not successful for the following reason: " + status);
  }
});

geocoder.geocode( { 'address': address2}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {

  endLat = results[0].geometry.location.lat();
  endLong = results[0].geometry.location.lng();
  Secondlatlng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng());

  } 

  else {
    alert("Geocode was not successful for the following reason: " + status);
  }
});
}

function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1); 
  var a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ; 
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
  var d = R * c; // Distance in km
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180)
}

一些帮助将不胜感激。

提前致谢:D

2 个答案:

答案 0 :(得分:2)

当数组的长度为2时,你可以将latLngs推入一个数组,计算距离。

简单实现(使用geometry-library的方法),它还在地理编码后存储latlng(不需要再次请求地址)。

var geocoder = new google.maps.Geocoder();

function onselectchange() {

  var latLngs = [],
    calc = function() {
      
      if (latLngs.length === 2) {
        var distance = Math.round(google.maps.geometry.spherical
          .computeDistanceBetween(latLngs[0],
            latLngs[1]));
        print(distance);

      }
    };

  ['start', 'end'].forEach(function(id) {
    var list = document.getElementById(id),
      option = list.options[list.selectedIndex];
    if (option.latlng) {
      latLngs.push(option.latlng);
    } else {
      geocoder.geocode({
          address: option.value
        },
        function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            var latLng = results[0].geometry.location
            option.latlng = latLng;
            latLngs.push(latLng);
            calc();
          }
        }
      );
    }
  }),
  print=function(dist) {
    document.getElementById('result').textContent = 
      (dist)?Math.round(dist/1000)+'km':'';
  }
  
  print();
  calc();
}
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=geometry"></script>
<select onchange="onselectchange()" id="start">
  <option>Berlin</option>
  <option>Rome</option>
  <option>Paris</option>
  <option>Tokio</option>
  <option>Chicago</option>
</select>
<select onchange="onselectchange()" id="end">
  <option>Berlin</option>
  <option>Rome</option>
  <option>Paris</option>
  <option>Tokio</option>
  <option>Chicago</option>
</select><span id="result"></span>

答案 1 :(得分:0)

这是我在评论中提到的提示。

var startLat, startLong, endLat, endLong;
var Firstlatlng , Secondlatlng;
geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {

        startLat = results[0].geometry.location.lat();
        startLong = results[0].geometry.location.lng();

        Firstlatlng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng());
        //alert("Inside:"+startLat);
        geocoder.geocode( { 'address': address2}, function(results2, status2) {
            if (status2 == google.maps.GeocoderStatus.OK) {

                endLat = results2[0].geometry.location.lat();
                endLong = results2[0].geometry.location.lng();
                Secondlatlng = new google.maps.LatLng(results2[0].geometry.location.lat(),results2[0].geometry.location.lng());

                //alert(startLat+" "+startLong+" "+endLat+" "+endLong);
                var R = 6371; // Radius of the earth in km
                var dLat = deg2rad(endLat-startLat);  // deg2rad below
                var dLon = deg2rad(endLong-startLong); 
                var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(deg2rad(startLat)) * Math.cos(deg2rad(endLat)) 
                * Math.sin(dLon/2) * Math.sin(dLon/2); 
                var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
                var d = R * c; // Distance in km
                var firstSelect = document.getElementById('start');
                var secondSelect = document.getElementById('end');


                //return elt.options[elt.selectedIndex].text;
                alert("The distance between "+firstSelect.options[firstSelect.selectedIndex].text + " and " + secondSelect.options[secondSelect.selectedIndex].text + " is " +Math.round(Number(d)) +" Km");
                //alert(d);  

            } 

            else {
                alert("Geocode was not successful for the following reason: " + status2);
            }
        });

  } 

  else {
    alert("Geocode was not successful for the following reason: " + status);
  }
});

谢谢大家的帮助!