Loading...

How to calculate the distance between two latitudes longitudes using google distance api

Image

Introduction:

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.

Step-by-Step Guide:

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:

  • PHP 7+
  • GuzzleHttp: A PHP HTTP client that makes it easy to send HTTP requests.

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:

  1. Go to Google Cloud Console.
  2. Create a new project or use an existing one.
  3. Enable the Distance Matrix API.
  4. Generate an API key and restrict its usage for security.

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:

  • Ensure your API key is secured and not exposed publicly.
  • Implement error handling for cases where the API might not return a distance due to invalid inputs or network issues.

Conclusion:

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.

0 Comments

Leave a comment