获取以公里为单位的两个坐标之间的距离

get distance between two coordinates in km

所以我正在尝试使用 php 获取坐标之间的距离。 我正在使用这两个函数:

  1. 通过ip定位用户
  2. 获取带有 gps 坐标的图像

在通过 ip 定位用户时,我从 ip 获取纬度和经度,并将它们放入 $ lat1 和 $ lon1

$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
$user_location = $details->loc;
$pieces = explode(",", $user_location);
$lat1 = $pieces[0];
$lon1 = $pieces[1];
$unit = "Km";

在获取图像中我正在选择行,它们都包含来自 exif 的纬度和经度。

function get_image($db){
    $select = "id, image_name";
    $sql = "SELECT $select FROM images ORDER BY id DESC";
    $stmt = $db->prepare($sql);
    $stmt->execute();
    $spot = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if(!$stmt -> rowCount()){
        echo "<div class='noSpots'>
                    <p>Sorry there seams to be nothing in your area</p>
              </div>";
    }
        return $spot;
}//spots_narrow ends here

所以在这两个函数之后我现在可以 return 四个变量与我想计算的两个纬度和经度之间的距离。

- $ lat1
- $ lon1
- $ lat2
- $ lon2

来自http://rosettacode.org/wiki/Haversine_formula#PHP

class POI {
    private $latitude;
    private $longitude;
    public function __construct($latitude, $longitude) {
        $this->latitude = deg2rad($latitude);
        $this->longitude = deg2rad($longitude);
    }
    public function getLatitude() return $this->latitude;
    public function getLongitude() return $this->longitude;
    public function getDistanceInMetersTo(POI $other) {
        $radiusOfEarth = 6371000;// Earth's radius in meters.
        $diffLatitude = $other->getLatitude() - $this->latitude;
        $diffLongitude = $other->getLongitude() - $this->longitude;
        $a = sin($diffLatitude / 2) * sin($diffLatitude / 2) +
            cos($this->latitude) * cos($other->getLatitude()) *
            sin($diffLongitude / 2) * sin($diffLongitude / 2);
        $c = 2 * asin(sqrt($a));
        $distance = $radiusOfEarth * $c;
        return $distance;
    }
}

你想看看 Haversine Formula 我不喜欢 PHP,但在伪 php 代码中是这样的:

$EarthRadius = 6371000; // radius in meters
$phi1 = deg2rad($lat1)
$phi2 = deg2rad($lat2)
$deltaLat = deg2rad($lat2 - $lat1)
$deltaLon = deg2rad($lon2 - $lon1)

var $a = sin($deltaLat/2) * sin($deltaLat/2) + cos($phi1) * cos($phi2) * sin($deltaLon / 2) * sin($deltaLon / 2);
var $c = 2 * atan2(sqrt($a), sqrt(1 - $a));

var $result = $EarthRadius * $c;

您应该能够在 PHP 数学模块中找到 cos、sin、atan2 的等效公式。还有一些其他的近似值,但这应该可以很好地工作。