Calculate Distance Using Google Maps API in Laravel

by Akshat V. 3 minute read 51 views

Calculate accurate travel distances and time between locations using Laravel and Google Maps API, ideal for logistics, delivery apps and location-based mobile services.

Key Points

  • Over 5 million websites and apps use Google Maps APIs for location-based features.
  • 70% of users expect accurate ETA and routing in delivery and ride-hailing apps.
  • Google Maps APIs handle more than 1 billion monthly active users globally.
Digittrix Blog Author Image

Web Developer

Akshat V.

3 min read

Skilled web developer with 2+ years of hands-on experience delivering fast and functional websites.

 Image displaying Google Maps logo linked by a line to a red location pin, representing navigation or locationbased services

In today’s fast-paced digital world, location-based services are becoming a cornerstone of modern applications. Whether you are building a food delivery platform, a logistics system, or a ride-hailing service, knowing the exact travel distance and time between two places is critical. Integrating location intelligence is a must-have feature for custom app development, especially for on-demand app development, where route accuracy significantly impacts service quality and user satisfaction.

This guide will show you how to use the Google Maps Distance Matrix API with Laravel to calculate the distance and estimated travel duration between two coordinates. This functionality can significantly enhance apps developed by Android or iOS app developers seeking to create powerful, scalable and real-time location-based solutions.

Why Use Google Maps Distance Matrix API?

The Distance Matrix API from Google Maps offers reliable and accurate distance and travel time estimates between multiple origins and destinations based on actual road networks. Here’s why it's popular among Android app developers and iOS app developers:

  • Real-time, route-based calculations

  • Supports various travel modes (driving, walking, bicycling, transit)

  • Takes traffic into account (optional)

  • Ideal for scalable on-demand app development systems like taxi booking or delivery tracking apps

Whether you are involved in web app development or creating apps for specific platforms like Android or iOS, this API is a valuable tool in your stack.

Step 1: Get Google Maps API Key

  1. Go to the Google Cloud Console.

  2. Create a new project or select an existing one.

  3. Navigate to APIs & Services > Library, then search and enable the “Distance Matrix API”.

  4. Generate a new API Key under APIs & Services > Credentials.

  5. Restrict the key to allow only the Distance Matrix API for better security.

This API key is essential for your Laravel application to authenticate and send requests to Google’s services.

Step 2: Store the API Key in the Laravel .env File

In your Laravel project’s .env file, store the key securely:

                                        GOOGLE_MAP_KEY=your_api_key_here
                                    

This practice is regarded as best practice in custom app development, ensuring that your keys are not exposed in public repositories or frontend code.

Step 3: Laravel Function to Fetch Distance and Duration

The following function sends a request to Google’s Distance Matrix API and returns the travel distance and time:

                                        public function showDistance()
{
    $originLat = '30.1647';
    $originLng = '77.2979';
    $destinationLat = '30.7333';  
    $destinationLng = '76.7794';

    $origin = $originLat . ',' . $originLng;
    $destination = $destinationLat . ',' . $destinationLng;

    $apiKey = env('GOOGLE_MAP_KEY');
    $url = 'https://maps.googleapis.com/maps/api/distancematrix/json';

    $response = Http::get($url, [
        'origins' => $origin,
        'destinations' => $destination,
        'key' => $apiKey,
    ]);

    if ($response->successful()) {
        $data = $response->json();

        if ($data['rows'][0]['elements'][0]['status'] === 'OK') {
            return response()->json([
                "success" => true,
                "message" => "success",
                "data" => [
                    'distance_text' => $data['rows'][0]['elements'][0]['distance']['text'],
                    'distance_value' => $data['rows'][0]['elements'][0]['distance']['value'],
                    'duration_text' => $data['rows'][0]['elements'][0]['duration']['text'],
                    'duration_value' => $data['rows'][0]['elements'][0]['duration']['value']
                ]
            ]);
        }
    }

    return response()->json([
        "success" => false,
        'error' => 'Could not fetch distance.'
    ]);
}
                                    

This controller method is ideal for on-demand services that require real-time routing information, such as food delivery web apps or cab booking systems developed by Laravel app developers

Sample API Response

Here’s an example response from a successful API call:

                                        {
  "success": true,
  "message": "success",
  "data": {
    "distance_text": "100 km",
    "distance_value": 100281,
    "duration_text": "1 hour 52 mins",
    "duration_value": 6749
  }
}
                                    

You can use this data to calculate delivery charges, estimated arrival times, or show route info on a map in your frontend mobile app.

Additional Use Cases

  • Multi-drop delivery route optimization

  • Driver-to-customer distance in ride-hailing apps

  • Real-time tracking and ETA calculations

  • Route-based service availability zones

Such features are often integrated by teams specializing in on-demand app development to improve user experience and optimize backend operations.

Best Practices

  • Always validate API responses to avoid app crashes.

  • Cache results where possible to save costs and improve speed.

  • Secure your API keys and monitor quota usage via the Google Cloud Console.

  • Consider extending functionality with the Directions API or the Geocoding API for added location intelligence.

Final Words

Integrating Google Maps Distance Matrix API with Laravel is a powerful way to add real-time distance and duration calculations to your application. Whether you're an Android app developer building a logistics solution or an iOS app developer creating a location-based utility, this setup helps simplify your workflow and improve end-user experiences.

This feature is also a key component of scalable custom app development and on-demand app development projects where location accuracy and real-time data are required.

Tech Stack & Version

Frontend

  • HTML
  • CSS
  • JavaScript

Backend

  • PHP ≥ 7.2
  • Laravel ≥ 6.0

Deployment

  • Apache / Nginx
  • DigitalOcean / Linode
img

©2025Digittrix Infotech Private Limited , All rights reserved.