使用Laravel在Circle中查找坐标

e5nqia27  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(127)

我试图找出一个坐标圈内画在谷歌Map。
如何使用Laravel在GoogleMap上绘制的圆圈内找到坐标?

iyfamqjs

iyfamqjs1#

当您有空间存储的坐标时,您可以使用它来确定坐标是否在圆内

$selected_point = new Point($latitude, $longitude);
$circle = CircleStoreModel::whereRaw(
        "ST_Distance(coordinates, ?) <= radius",
        [$targetPoint]
    )->first();

    if ($circle) {
        return 'Coordinate is inside a circle';
    }

    return 'Coordinate is outside all circles';

字符串
如果坐标是用lat和lat分开的,那么你可以用这个

public function checkCoordinateInCircle($latitude, $longitude)
{
    $selected_point = ['lat' => $latitude, 'lng' => $longitude];
    
    $circles = CircleStoreModel::all();
    
    foreach ($circles as $circle) {
        $circleCenter = $circle->coordinates;
        $circleRadius = $circle->radius;
        
        $distance = $this->calculateDistance($circleCenter,$selected_point);
        
        if ($distance <= $circleRadius) {
            return 'Coordinate is inside a circle';
        }
    }
    
    return 'Coordinate is outside all circles';
}

private function calculateDistance($point1, $point2)
{
    $lat1 = deg2rad($point1->getLat());
    $lon1 = deg2rad($point1->getLng());
    $lat2 = deg2rad($point2['lat']);
    $lon2 = deg2rad($point2['lng']);

    // Haversine formula to calculate the distance between two coordinates
    $dlat = $lat2 - $lat1;
    $dlon = $lon2 - $lon1;
    $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlon / 2) * sin($dlon / 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    $distance = 6371000 * $c; // Radius of Earth in meters

    return $distance;
}

相关问题