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

Co-Founder

Vandana Abrol Digittrix Blog Author Image

3 min read

With Over 14 years of Experience in the IT Field, Helping Companies Optimise there Products for more Conversions

image showing google map with laravel icon to calculate distance

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 and especially for on-demand app development, where route accuracy 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 improve apps developed by Android or iOS app developers looking 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:

  1. Real-time, route-based calculations
  2. Supports various travel modes (driving, walking, bicycling, transit)
  3. Takes traffic into account (optional)
  4. Ideal for scalable on-demand app development systems like taxi booking or delivery tracking apps

Whether you are involved in custom 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 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 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 a 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:

                                        use Illuminate\Support\Facades\Http;

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 apps or cab booking systems developed by iOS or Android 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

  1. Multi-drop delivery route optimization
  2. Driver-to-customer distance in ride-hailing apps
  3. Real-time tracking and ETA calculations
  4. 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

  1. Always validate API responses to avoid app crashes.
  2. Cache results where possible to save costs and improve speed.
  3. Secure your API keys and monitor quota usage via the Google Cloud Console.
  4. 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.

Do you want help implementing this?

Get a summary via Google for

$0

 
Get Help Now!

Tech Stack & Version

 Backend

  • Laravel: v11.x 

  • PHP: v8.3+

 

Frontend

  • Laravel Blade 
  • Inertia.js

Deployment

  • DigitalOcean
  • Linode
  • Heroku
img

©2025Digittrix Infotech Private Limited , All rights reserved.