php - 检查坐标是否在与其他坐标的特定距离内

标签 php math coordinates match distance

好的,所以我在特定坐标上有一个目标,在其他坐标上有一些“人”,我想检查这些人的坐标是否在距目标坐标 2 公里(2000 米)的距离内。

下面的代码只是为了更清楚地说明我想要的东西,问题当然是如何做到这一点?我真的很感激这个问题的解决方案,谢谢!

$person0 = Array('56.34342', '49.324523');
$person1 = Array('57.49544', '47.421524');
$person2 = Array('56.74612', '48.722323');

$target = Array('56.35343', '49.342343');

for (var $i = 0; $i < 4; i$++) {
    CheckIfMatch($person + i$);
}

function CheckIfMatch($person) {
    if($person is within 2km from target) {
        echo 'Match!';
    }
}

最佳答案

您可以使用大圆算法来做到这一点。 http://en.wikipedia.org/wiki/Great-circle_distance

这是计算距离的方法。

编辑

这里是完整的代码,你可以做到这一点!

<?php
$persons = Array();

$persons[] = Array('52.00951','4.36052');//Delft is more than 2 km from den haag
$persons[] = Array('52.03194','4.31769');//Rijswijk is less than 2 km from den haag
$persons[] = Array('52.07097','4.29945');//A place near den Haag almost 2 streets from center and my favourite coffee shop
$persons[] = Array('52.37022','4.89517');//Amsterdamn is about 60 km *DRIVING* from the hagues according to Gmaps

$target = Array('52.07050', '4.30070');//Den Haag
$i = 0;
foreach($persons as $person){
    $i++;
    $distance = calculate_distance($person, $target);
    if($distance <= 2 ){ 
        echo "Person $i is within 2km with a distance to taget of $distance</br>";
    }else{
        echo "Person $i is <b>not</b> within 2km with a distance to taget of $distance</br>";
    }

}

function calculate_distance($person, $target){

    $lat1 = $person[0];
    $lng1 = $person[1];
    $lat2 = $target[0];
    $lng2 = $target[1];
    $pi = 3.14159;
    $rad = doubleval($pi/180.0);

    $lon1 = doubleval($lng1)*$rad;
    $lat1 = doubleval($lat1)*$rad; 
    $lon2 = doubleval($lng2)*$rad; 
    $lat2 = doubleval($lat2)*$rad; 
    $theta = $lng2 - $lng1; 

    $dist = acos(sin($lat1) * sin($lat2) + cos($lat1) * cos($lat2) * cos($theta)); 

    if ($dist < 0) 
        $dist += $pi;


    $miles = doubleval($dist * 69.1); 
    $inches = doubleval($miles * 63360); 
    $km  =  doubleval($dist * 115.1666667);

    $dist = sprintf( "%.2f",$dist); 
    $miles = sprintf( "%.2f",$miles); 
    $inches = sprintf( "%.2f",$inches); 
    $km = sprintf( "%.2f",$km);
    //Here you can return whatever you please
    return $km;
}

?>

当然还有结果:

Person 1 is not within 2km with a distance to taget of 4.24
Person 2 is within 2km with a distance to taget of 1.21
Person 3 is within 2km with a distance to taget of 0.09
Person 4 is not within 2km with a distance to taget of 41.56

关于php - 检查坐标是否在与其他坐标的特定距离内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14087076/

相关文章:

php - 为 Woocommerce 中的特定用户角色设置最低订单金额

php - 使用 PHP 从 MySQL 数据库中获取数据,以表格形式显示以供编辑

c++ - 使用模运算的正确方法

dictionary - 如何从中心点计算矩形的纬度和经度

javascript - 谷歌地图无限线/增加长度或纬度lng计算

java - 我如何检索 Actor 子类的坐标以便将新 Actor 放置在该位置?

php - 使用php将图像插入mysql

php - 为什么我的代码无法检索/显示 PDO 记录集?

Javascript 计算错误

java - n个质数之和java,困惑