Skip to main content

Command Palette

Search for a command to run...

To check if a given latitude and longitude fall within a collection of locations defined by latitude, longitude, and radius

Updated
1 min read
To check if a given latitude and longitude fall within a collection of locations defined by latitude, longitude, and radius

Here's a sample code to check if a given latitude and longitude fall within a radius in a Laravel Collection:

phpCopy codeuse Illuminate\Support\Facades\DB;
use Illuminate\Support\Collection;

public function checkLocationInCollection($inputLatitude, $inputLongitude, Collection $locations)
{
    foreach ($locations as $location) {
        $distance = $this->calculateDistance($inputLatitude, $inputLongitude, $location->latitude, $location->longitude);

        if ($distance <= $location->radius) {
            return true;
        }
    }

    return false;
}

private function calculateDistance($lat1, $long1, $lat2, $long2)
{
    $earthRadius = 3959;
    $latFrom = deg2rad($lat1);
    $longFrom = deg2rad($long1);
    $latTo = deg2rad($lat2);
    $longTo = deg2rad($long2);
    $latDelta = $latTo - $latFrom;
    $longDelta = $longTo - $longFrom;

    $angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) + cos($latFrom) * cos($latTo) * pow(sin($longDelta / 2), 2)));
    $distance = $angle * $earthRadius;

    return $distance;
}

In this example, the checkLocationInCollection function takes in the input latitude, longitude, and a Collection of locations, each containing latitude, longitude, and radius properties. The function iterates through each location in the Collection and calculates the distance between the input latitude and longitude and the location using the calculateDistance function. If the calculated distance is less than or equal to the location's radius, the function returns true. If no location in the Collection meets the criteria, the function returns false.

More from this blog

Jaskaran Singh

19 posts

Expert Full Stack Developer specializing in React, Next.js, and mobile app development. Building modern web applications and mobile solutions in Amritsar, India.