計算Google Maps V3中兩點之間的距離

您如何計算Google Maps V3中兩個標記之間的距離? (相似於V2中的distanceFrom函數。) html

謝謝.. 算法


#1樓

使用PHP,您能夠使用如下簡單函數計算距離: api

// to calculate distance between two lat & lon

function calculate_distance($lat1, $lon1, $lat2, $lon2, $unit='N') 
{ 
  $theta = $lon1 - $lon2; 
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); 
  $dist = acos($dist); 
  $dist = rad2deg($dist); 
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344); 
  } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
        return $miles;
      }
}

// function ends here

#2樓

不得不作...動做腳本的方式 函數

//just make sure you pass a number to the function because it would accept you mother in law...
public var rad = function(x:*) {return x*Math.PI/180;}

protected  function distHaversine(p1:Object, p2:Object):Number {
    var R:int = 6371; // earth's mean radius in km
    var dLat:Number = rad(p2.lat() - p1.lat());
    var dLong:Number = rad(p2.lng() - p1.lng());

    var a:Number = Math.sin(dLat/2) * Math.sin(dLat/2) +
                Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong/2) * Math.sin(dLong/2);
    var c:Number = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    var d:Number = R * c;

    return d;
}

#3樓

使用google能夠使用球狀apigoogle.maps.geometry.spherical.computeDistanceBetween (latLngA, latLngB);google

可是,若是球形投影或正弦波解決方案的精度對您來講不夠精確(例如,若是您靠近極點或計算更長的距離),則應使用其餘庫。 spa

我在這裏的 Wikipedia上找到了有關該主題的大多數信息。 code

查看任何給定算法的精度是否足夠的一個技巧是填寫地球的最大和最小半徑,並查看差別是否可能致使您的用例出現問題。 能夠在本文中找到更多詳細信息 htm

最終,Google API或Haversine能夠毫無問題地知足大多數目的。 對象


#4樓

請參閱GLatLng對象上的distanceFrom函數; 在v2和v3之間,功能參數略有變化。 ip


#5樓

若是要本身計算,能夠使用Haversine公式:

var rad = function(x) {
  return x * Math.PI / 180;
};

var getDistance = function(p1, p2) {
  var R = 6378137; // Earth’s mean radius in meter
  var dLat = rad(p2.lat() - p1.lat());
  var dLong = rad(p2.lng() - p1.lng());
  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) *
    Math.sin(dLong / 2) * Math.sin(dLong / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c;
  return d; // returns the distance in meter
};
相關文章
相關標籤/搜索