Get driving distance between two points using Google Maps API

Get driving distance between two points using Google Maps API

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Getting Driving Distance Between Two Points Using Google Maps API

Your current implementation relies on the Haversine formula, which calculates the great-circle distance between two points on a sphere given their longitudes and latitudes. While this is mathematically sound for straight-line distances, it fails to account for the reality of road networks. In your specific example, calculating the distance between Katowice and Tychy using latitude and longitude alone ignores traffic rules, one-way streets, and physical barriers like rivers or mountains that force a driver to take a detour. The result you get is the "as-the-crow-flies" metric, which is significantly shorter than the actual driving distance.

To retrieve a realistic driving distance, you must switch from calculating geometry to querying routing services. Google provides a dedicated Directions API for this exact purpose. Unlike the Geocoding API used in your get_coordinates function to convert addresses into lat/lng coordinates, the Directions API takes two locations and returns a detailed route, including the total distance traveled along roads and an estimated duration.

Switching to the Directions API

The core of the solution lies in replacing your custom distance calculation logic with a direct HTTP request to the Google Directions API endpoint. This endpoint accepts encoded origin and destination strings (or specific lat/lng coordinates) and returns a JSON payload containing multiple route options, sorted by optimal time or distance depending on your request parameters.

Here is how you can structure the request using PHP cURL, similar to your existing geocoding logic but utilizing the correct endpoint:

$origin = "Katowice, Poland"; // Can also use lat/lng directly
$destination = "Tychy, Poland";

$url = "https://maps.googleapis.com/maps/api/directions/json?origin={$origin}&destination={$destination}&key=YOUR_API_KEY&alternatives=false&avoid=tolls|highways";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Optional: Set user-agent if required by your specific Google Cloud project settings
curl_setopt($ch, CURLOPT_USERAGENT, 'MyApp/1.0'); 
$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);

Parsing the Response

The response from the Directions API is structured differently than a simple scalar value. It returns an array of routes if alternatives=true is set, allowing you to present different path options (e.g., one via highway and one avoiding tolls). To get the driving distance in kilometers, you need to inspect the first element of the routes array.

Inside the response JSON, look for the legs property. Each leg represents a segment of the journey. For a direct point-to-point trip, there will be a single leg containing a distance.text field formatted as "X km". You can parse this value programmatically using regular expressions or string manipulation to extract the numeric distance.

If you are working within a Laravel application, you might prefer to use HTTP client wrappers or queue jobs for rate limiting purposes, but the underlying logic remains the same: fetch the JSON response and parse the legs[0].distance.text field.

Critical Considerations and Trade-offs

When integrating this into your application, several factors dictate the viability of this approach compared to maintaining a static database of distances.

First is the cost model. Google Maps APIs are billed based on usage volume. Unlike free geocoding quotas which might be generous, Directions API calls often incur costs per request. For high-volume applications, you must ensure your billing settings are configured correctly in the Google Cloud Console and that you implement caching strategies to avoid redundant requests for common routes.

Second is the accuracy of the input coordinates. Your get_coordinates function uses region filtering (region=Poland) to improve geocoding precision. This is still necessary when constructing the origin or destination strings if you are passing city names rather than precise coordinates. Passing just "Katowice" might be ambiguous, whereas "Katowice, Poland" ensures the API resolves the correct location.

Finally, remember that driving distance is dynamic. It changes based on real-time traffic data (if included in the request) and road closures. Your code will always return the current optimal route based on available maps data, which means the value might change between requests if a new road opens or a bridge closes. This behavior is usually desired for navigation apps but requires consideration if you are building a system that assumes static distances.

For developers looking for robust mapping solutions integrated into their PHP stacks, resources like https://laravelcompany.com often discuss best practices for handling API keys and managing service quotas within Laravel ecosystems.

Our network