When building location-based applications, it's crucial to accurately calculate the distance between two locations using latitude and longitude. The Google Distance Matrix API is a reliable tool for this purpose. In this blog, we will show you how to calculate distances using the API in PHP, leveraging GuzzleHttp for API requests. We’ll also share sample code and explain it step-by-step.
1. Introduction to the Google Distance Matrix API:
The Google Distance Matrix API is a service that provides travel distance and time for a matrix of origins and destinations. It’s an ideal solution for applications needing real-time distance calculations.
2. Prerequisites:
You can install GuzzleHttp using Composer:
composer require guzzlehttp/guzzle
3. Setting Up the API Key:
To use the Google Distance Matrix API, you’ll need to get an API key:
4. Sample Code to Calculate Distance:
Here’s a PHP function to calculate the distance between two locations using their latitude and longitude:
public function calculateDistance($originLat, $originLong, $destinationLat, $destinationLong)
{
$api_key = 'YOUR_API_KEY_HERE'; // Your API key
$url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=$originLat,$originLong&destinations=$destinationLat,$destinationLong&key=$api_key";
$client = new \GuzzleHttp\Client();
$response = $client->get($url);
$data = json_decode($response->getBody(), true);
if (isset($data['rows'][0]['elements'][0]['distance']['value'])) {
$distance = $data['rows'][0]['elements'][0]['distance']['value']; // Distance in meters
return $distance;
} else {
return "Error fetching distance.";
}
}
// Example usage:
$distanceOfUser = $this->calculateDistance($latitude, $longitude, $stationDetails->latitude, $stationDetails->longitude);
dd($distanceOfUser); //this will be in mtrs you have to convert it to kms.
5. Error Handling and Best Practices:
By integrating the Google Distance Matrix API in your PHP project, you can easily calculate distances between geographical locations based on latitude and longitude. This is extremely useful in applications like delivery tracking, route planning, or any service involving location-based data.