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

I am a full-stack developer with 5 years of experience in the field. I specialize in PHP, Laravel, React and React Native, and have a track record of building high-performing, scalable and user-friendly web and mobile applications. With a strong understanding of web development principles and a passion for staying up-to-date with the latest technologies, I am able to deliver high-quality solutions that meet the needs of my clients. I am a team player with strong communication skills and the ability to adapt to new challenges. I am always looking to improve my skills and take on new projects that will push me to grow as a developer.
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.




