[PHP]以經緯度計算兩點間的距離

雖然不常用,不過還是紀錄一下

/**
 * Calculate the distance between 2 position
 * @param type $latitudeFrom
 * @param type $longitudeFrom
 * @param type $latitudeTo
 * @param type $longitudeTo
 * @param type $earthRadius
 * @return type
 */
function haversineGreatCircleDistance($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000) {
  $latFrom = deg2rad($latitudeFrom);
  $lonFrom = deg2rad($longitudeFrom);
  $latTo = deg2rad($latitudeTo);
  $lonTo = deg2rad($longitudeTo);

  $latDelta = $latTo - $latFrom;
  $lonDelta = $lonTo - $lonFrom;

  $angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
              cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
  return $angle * $earthRadius;
}