如何使用PHP检查某个坐标是否落入另一个坐标半径

Ken*_*nas 21 php geolocation

我见过这么多功能,但它恰好只适用于MySQL或Postgresql.我想要PHP的等效逻辑.我正在做一些比较,比如我有这些数据是在创建时生成的.

Lat: 56.130366
Long: -106.34677099999
Run Code Online (Sandbox Code Playgroud)

稍后,我想检查这个坐标是否落在另一个坐标的半径范围内.

Lat: 57.223366
Long: -106.34675644699
radius: 100000 ( meters )
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Ken*_*nas 44

谢谢您的帮助.下面是一个示例函数,它采用两组经度和纬度坐标,并返回两者之间的距离.

function getDistance($latitude1, $longitude1, $latitude2, $longitude2) {  
  $earth_radius = 6371;

  $dLat = deg2rad($latitude2 - $latitude1);  
  $dLon = deg2rad($longitude2 - $longitude1);  

  $a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * sin($dLon/2) * sin($dLon/2);  
  $c = 2 * asin(sqrt($a));  
  $d = $earth_radius * $c;  

  return $d;  
}

$distance = getDistance(56.130366, -106.34677099999, 57.223366, -106.34675644699);
if ($distance < 100) {
  echo "Within 100 kilometer radius";
} else {
  echo "Outside 100 kilometer radius";
}
Run Code Online (Sandbox Code Playgroud)

  • [等效,但在Javascript](https://gist.github.com/moshmage/2ae02baa14d10bd6092424dcef5a1186),因为我花了太长时间寻找这个. (6认同)

Gui*_*sel 8

您应该使用Haversine公式来计算两点之间的距离.你有一个PHP版本.

然后检查是否distance < 100000.