【问题标题】:get distance between two coordinates in km [duplicate]以km为单位获取两个坐标之间的距离[重复]
【发布时间】:2015-09-25 21:16:11
【问题描述】:

所以我正在尝试使用 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

所以在这两个函数之后,我现在可以返回四个变量,其中包含我想要计算之间距离的两个纬度和经度。

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

【问题讨论】:

标签: php gps location


【解决方案1】:

你想看看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 的等效公式。还有一些其他的近似值,但这应该工作得很好。

【讨论】:

  • 以上帖子将以米为单位为您提供距离。
  • 我无法缝合以使其工作?我应该将 $lat 和 $lon 传递给 $phi1 和 $phi2 吗?
  • 我在写伪代码。您的 $lat1 将是我的 lat1、$lat2 -> lat2 等...您还可以使用 deg2rad 公式转换为弧度。例如:$phi1 = deg2rad($lat1);我会更新帖子来解决这个问题。
【解决方案2】:

来自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;
    }
}

【讨论】:

  • 嗨如何将距离转换为公里
猜你喜欢
  • 2011-08-10
  • 1970-01-01
  • 2018-10-28
  • 2015-02-26
  • 1970-01-01
  • 2010-11-23
  • 1970-01-01
  • 2012-06-18
  • 1970-01-01
相关资源
最近更新 更多