Get the distance between two places in PHP with Google Map API

Here in this post, we are going to introduce with an amazing and interesting trick. We are going to learn how to work with Google Distance Matrix API in PHP. Google’s Distance Matrix API provides you the distance between places.

Using this API, we can get the distance and duration to reach the destination from the origin for two or multiple origins and destinations. But for simplicity and for better understanding we are going to retrieve the distance and time duration between two places only. So, let’s began.

To get the distance we are going to set parameters with an API key to the API URL through the get method. Google allows retrieving the data through the URL. They provide both JSON and XML formatted data. But here we are going to use the JSON data format which is also recommended by the Google’s API provider.

Get visitors country and city in PHP using Freegeoip API

Get country data by clicking on map – PHP source code

Below is the given URL structure which sends us the data which contains the distance and the duration to reach:[ORIGIN_PLACE]&destinations=[DESTINATION_PLACE]&key=[YOUR_API_KEY]

By default, the unit is metric. You can make the unit imperial just by providing the unit parameter just like in the URL below:[ORIGIN_PLACE]&destinations=[DESTINATION_PLACE]&key=[YOUR_API_KEY]

Now let’s see our PHP code to retrieve the JSON data and decode it:

$distance_data = file_get_contents('[ORIGIN_PLACE]&destinations=[DESTINATION_PLACE]&key=[YOUR_API_KEY]');
$distance_arr = json_decode($distance_data);

In the above code, we get the data as the array in a variable after decoding the JSON formatted data coming from the API URL.

And to check the status below is the code:

if ($distance_arr->status=='OK') {
   // Code to run after status OK
} else {
  // Code to run after status INVALID_REQUEST

Also, we have to check if the origin and destination address found or not:

if ($origin_addresses=="" or $destination_addresses=="") {
	 // Code to run if origin address not found

Now below is the code to keep the distance and duration from the array that we got by decoding the JSON data:

$elements = $distance_arr->rows[0]->elements;
$distance = $elements[0]->distance->text;
$duration = $elements[0]->duration->text;

Complete example code with origin and destination HTML input

Now here we are going to see a complete example code which has origin and destination HTML input fields. After one put the origin and destination and then submit the form, it will display the distance and duration that may take to reach the destination.

<form action="google_distance_origin_destination.php">
  From: <input type="text" name="origin">
  To: <input type="text" name="destination">
  <input type="submit" name="submit" value="Get distance">

  if (isset($_GET['submit'])) {
    $origin = $_GET['origin'];
    $destination = $_GET['destination'];

   /* In imperial unit
  $distance_data = file_get_contents(''.urlencode($origin).'&destinations='.urlencode($destination).'&key=AIzaSyD6YkF-BVV1LNLOz5n3zeL9bi1farzUX8k');

   // In metric unit. This is default
   $distance_data = file_get_contents(''.urlencode($origin).'&destinations='.urlencode($destination).'&key=AIzaSyD6YkF-BVV1LNLOz5n3zeL9bi1farzUX8k');

   $distance_arr = json_decode($distance_data);

if ($distance_arr->status=='OK') {
    $destination_addresses = $distance_arr->destination_addresses[0];
    $origin_addresses = $distance_arr->origin_addresses[0];
} else {
  echo "<p>The request was Invalid</p>";

   if ($origin_addresses=="" or $destination_addresses=="") {
   	 echo "<p>Destination or origin address not found</p>";

   // Get the elements as array
   $elements = $distance_arr->rows[0]->elements;
   $distance = $elements[0]->distance->text;
   $duration = $elements[0]->duration->text;

   echo "From: ".$origin_addresses."<br/> To: ".$destination_addresses."<br/> Distance: <strong>".$distance ."</strong><br/>";
   echo "Duration: <strong>".$duration."";



In the above code, we have two HTML input fields. After one submits the form it will check two validation. One is for checking status and the other is for checking if the location found.

Locate the Geo-position of a visitor in JavaScript

If someone submits the form by keeping both or one of the input field blank, it will return the message “The request was Invalid”. If both or one of the address not found, it will then show the message “Destination or origin address not found”.

If the input fields value is valid then it will return the distance and the duration.

For example, suppose we have entered Washington as from location field and New York for to location field. It will then return the result that you can see below:

From: Washington, USA
To: New York, NY, USA

New York, NY, USA


1 day 17 hours

You can see that it returns distance of the two places, Washington and New York and the duration from Washington to New York.

17 responses to “Get the distance between two places in PHP with Google Map API”

  1. Claire says:

    This looks great!
    But how would go about finding the distance and Duration from 1 origin address to multiple destination addresses?
    And how can it show the results from closest to farthest?

  2. Cody says:

    Line 40 replace the second $destination_addresses with $distance

    • Faruque Ahamed Mollick says:

      Thank you for letting me know about this. I have changed the $destination_addresses with $distance on line 40.

  3. Mohsin says:

    how to get distance in miles.. Thanks

  4. Taoufik says:

    Thank you sooooo much man, i couldn’t do it with php it just didn’t work so i did it with javascript (knowing that javascript is not secure i was hesitating) but now … its simple and clean thanks

  5. Ashutosh says:

    Thank you very much!You solved my problem!!!

  6. Aha says:

    This looks great!
    But how would go about finding the distance and Duration from 1 origin address to multiple destination addresses?
    And how can it show the results from closest to farthest?

  7. Vishwa says:

    You saved my life man!!!!! Thank you so very very much!
    Although it’d be better if you explain how we must put the coordinates inside the text boxes. I found it from the API documentation

  8. Shayn Hacker says:

    Thank you so much for taking the time for figuring this all out and posting this. What specific resources did you read to be able to do this and how long did it take you to figure this out? And also could you make a video on YouTube about this?

  9. Kat213 says:

    i keep getting The request was Invalid. What could be the problem?

  10. ses rojas says:


    Im a newbie and just want to test this out. I tried to copy the complete code and daved it as php file. Opened it up in Google Chrome but what it did was just display the entire code in the window.

    Can you send me a complete php file that I could test out?

  11. Marijan says:


    It is great code and help me a lot but just to be complete I have a problem how to have this code with multiple locations.

    I try everything but every results give me only from origin to final destination, no way to found how modify to have calculation for multiple locations (destinations)

    Please help,

  12. Massimino says:

    Hello Thanks for this guide I was just looking for something simime so far always done in javascript and it’s a lot of work I just wanted to ask you one thing, this scirp you posted looks for points distant from each other only with an address I have, is it possible to insert the latitude and longitude? I’m interested in this non-specific.

  13. NickMak says:

    Great code. Its really help me!
    I just hope it’s not YOUR key in the code…
    Thank for your share.

  14. Harjiv says:

    It aint working with my API Key. What am I doing wrong ?

  15. Edgar Leon says:

    Thanks bro!!!

    I tried to install a packgist bundle to do this on symfony, but this way is more easy.

Leave a Reply

Your email address will not be published. Required fields are marked *