This is a tutorial on how to get the driving distance between two locations in PHP. In this tutorial, I will be showing you how to use the Google Directions API with PHP and JSON.
The first thing that you need is two locations. These locations can be Latitude Longitude values such as “52.188730, -6.542810” or textual addresses such as “Dublin, Ireland”. You can mix and match the two if you need to.
For this example, I’m going to get the driving distance between Cork in Ireland and Dublin in Ireland. I will also be using the textual addresses:
- “Cork, Ireland”
- “Dublin, Ireland”
Let’s jump straight into the code example (make sure that you read the comments):
<?php //Our starting point / origin. Change this if you wish. $start = "Cork, Ireland"; //Our end point / destination. Change this if you wish. $destination = "Dublin, Ireland"; //The Google Directions API URL. Do not change this. $apiUrl = 'http://maps.googleapis.com/maps/api/directions/json'; //Construct the URL that we will visit with cURL. $url = $apiUrl . '?' . 'origin=' . urlencode($start) . '&destination=' . urlencode($destination); //Initiate cURL. $curl = curl_init($url); //Tell cURL that we want to return the data. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //Execute the request. $res = curl_exec($curl); //If something went wrong with the request. if(curl_errno($curl)){ throw new Exception(curl_error($curl)); } //Close the cURL handle. curl_close($curl); //Decode the JSON data we received. $json = json_decode(trim($res), true); //Automatically select the first route that Google gave us. $route = $json['routes'][0]; //Loop through the "legs" in our route and add up the distances. $totalDistance = 0; foreach($route['legs'] as $leg){ $totalDistance = $totalDistance + $leg['distance']['value']; } //Divide by 1000 to get the distance in KM. $totalDistance = round($totalDistance / 1000); //Print out the result. echo 'Total distance is ' . $totalDistance . 'km'; //var_dump the original array, for illustrative purposes. var_dump($json);
If you look at the code snippet above, you’ll see what we carried out a GET HTTP request to Google’s API via the cURL functions in PHP (we also added some error handling). We then decoded the JSON that Google gave us into an associative array. After decoding the JSON, we selected the first route that Google gave us (Google may give you multiple routes, depending on the origin and destination). Finally, we looped through each leg in the route while adding up the distance.
Note: If you need miles instead of kilometers, then check out our page on Common measurement conversions in PHP.
Note: If you need to get something other than the driving distance, then you can specify the “mode” parameter in the $url string:
- mode=walking for walking distances.
- mode=bicycling for cycling distances.
- mode=transit for public transport routes (not always available).
Related: PHP: Haversine Formula Function.