Tuesday, March 26, 2024

How to Do Distance Calculation in Laravel Controllers



When working with multiple coordinates in Laravel applications, calculating distances between each coordinate and a given point can be a cumbersome task. In this article, we'll explore a method to streamline this process using a custom function in a Laravel Controller.

Setting Up the Controller

In our Controller class, we begin by initializing an empty array named $coordinates. This array will hold the coordinates from which we need to calculate distances.

$coordinates = [];

Next, we iterate through our data (referred to as $testing here) and extract the latitude and longitude coordinates. These coordinates are then stored in the $coordinates array for further processing.

foreach ($testing as $test) {

    $testLocations = $test->testLocations()->with('testLocation')->get();

    $coordinates = $testLocations->pluck('testLocation')->map(function ($location) {

        return $location->latitude . ',' . $location->longitude;

    })->toArray();

    $deal->shortestLocation = $this->getShortestDistanceFromCoordinates($coordinates, $validatedData['longitude'], $validatedData['latitude']);

}

Calculating Shortest Distance

Now, let's delve into the getShortestDistanceFromCoordinates() function. This function takes an array of coordinates, along with the longitude and latitude of the user's location, as parameters.

function getShortestDistanceFromCoordinates($coordinates, $userLongitude, $userLatitude)

{

    $shortestDistance = PHP_INT_MAX;

    $shortestLocation = null;


    try {

        $origin = $userLatitude . ',' . $userLongitude;

        $destinations = implode('|', $coordinates);

        $gmaps = new \yidas\googleMaps\Client(['key' => env('GOOGLE_MAP_API_KEY')]);

        $distanceMatrixResult = $gmaps->distanceMatrix($origin, $destinations);


        if (is_array($distanceMatrixResult) && $distanceMatrixResult['status'] === 'OK') {

            $distances = [];

            foreach ($distanceMatrixResult['rows'][0]['elements'] as $index => $element) {

                if ($element['status'] === 'OK') {

                    $distances[$index] = $element['distance']['value'];

                }

            }

            asort($distances);


            $shortestDistance = reset($distances); 

            $shortestLocationIndex = key($distances); 

            $shortestLocation = $coordinates[$shortestLocationIndex];

        } else {

            \Log::error('Distance matrix status is not OK');

        }

    } catch (\Exception $e) {

        \Log::error('Distance error: ' . $e->getMessage());

    }


    return [

        'distance' => $shortestDistance,

        'location' => $shortestLocation

    ];

}

Conclusion

By employing the getShortestDistanceFromCoordinates() function, we simplify the process of calculating distances between multiple coordinates and a given point in Laravel applications. This approach enhances efficiency and readability in code, making distance calculations a breeze.

0 comments:

Post a Comment