Calculate Distance Between Two Addresses using Google Maps API and PHP

The geocoding process is used to convert the address into geographic coordinates. Google Maps Geocoding API provides an easy way to fetch geographic data from addresses. Generally, Geocoding API is used to get the latitude and longitude of an address in the web application. Apart from this, Google Maps Geocoding API can be used for various purposes related to the Geocoding data.

The distance calculation is useful when your web application works with the user’s location. You can easily calculate the distance between addresses using Google Maps API and PHP. In this tutorial, we will show you how to calculate distance between two addresses with Google Maps Geocoding API using PHP.

Google Maps API Key

The Google Maps API Key is required to post HTTP request to Geocoding API and get response. Before getting started with the integration process, create an API key on the Google Cloud console.

  • Go to the Google Cloud console.
  • Select the project from the Project drop-down menu at the top. If you don’t have an existing project, create a new one.
  • In the left navigation pane, select the APIs & Services » Credentials.
  • In the Credentials page, select CREATE CREDENTIALS » API key.
  • The API key will be created and a dialog will appear with the newly created API key.
  • Navigate to the Library page from the left menu panel and make sure the Geocoding API is enabled.

Copy this API key for later use in the script on the Google Maps Geocoding API request.

Calculate Distance Between Addresses using PHP

The following example code shows the steps to get the distance between two addresses using Google Geocoding API and PHP.

  • Set the required values in the defined variable.
    • $GOOGLE_API_KEY – Specify the Google API Key.
    • $addressFrom – Specify the address where the distance calculation will start from.
    • $addressTo – Specify the address where the distance calculation will end.
  • Format the address string by replacing the empty spaces with plus (+) sign.
  • Request Google Geocoding API (https://maps.googleapis.com/maps/api/geocode/json) using the file_get_contents() method in PHP.
    • Execute Geocoding API requests for both, start and end addresses to get geographic data.
    • Pass the address (from which you want to calculate distance) and key parameters in the Geocoding API URL as a query string.
  • Decode JSON response returned by the Geocoding API using PHP json_decode() function.
  • Retrieve latitude and longitude from the geometry object of API response.
  • Calculate distance using the latitude and longitude of start and end addresses.
<?php 

// Google Maps API Key
$GOOGLE_API_KEY 'YOUR_API_KEY_HERE';

// Addresses between which distances will be calculated
$addressFrom    '616 Scholes St, Brooklyn, NY 11237'//start address
$addressTo      '6503 Metropolitan Ave, Queens, NY 11379'//end address

// Format address string
$formatted_address_from str_replace(array(' ','&'), '+'$addressFrom);
$formatted_address_to   str_replace(array(' ','&'), '+'$addressTo);

// Geocoding API request with start address
$geocode_data_start file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?address={$formatted_address_from}&key={$GOOGLE_API_KEY}");
$outputFrom json_decode($geocode_data_start);
if(!empty(
$outputFrom->error_message)){
    die(
"API Error: ".$outputFrom->error_message);
}elseif(empty(
$outputFrom->results[0])){
    die(
"Returns empty geodata: ".$addressFrom);
}

// Geocoding API request with end address
$geocode_data_end file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?address={$formatted_address_to}&key={$GOOGLE_API_KEY}");
$outputTo json_decode($geocode_data_end);
if(!empty(
$outputTo->error_message)){
    die(
"API Error: ".$outputTo->error_message);
}elseif(empty(
$outputTo->results[0])){
    die(
"Returns empty geodata: ".$addressTo);
}

// Retrieve latitude and longitude from the geodata
$latitude_from  $outputFrom->results[0]->geometry->location->lat;
$longitude_from $outputFrom->results[0]->geometry->location->lng;
$latitude_to    $outputTo->results[0]->geometry->location->lat;
$longitude_to   $outputTo->results[0]->geometry->location->lng;

// Calculate distance between latitudes and longitudes
$theta  $longitude_from $longitude_to;
$dist   sin(deg2rad($latitude_from)) * sin(deg2rad($latitude_to)) +  cos(deg2rad($latitude_from)) * cos(deg2rad($latitude_to)) * cos(deg2rad($theta));
$dist   acos($dist);
$dist   rad2deg($dist);
$miles  $dist 60 1.1515;

// Get distance in miles
$distance round($miles2).' miles';

?>

Display the distance two addresses on the web page.

// Render the distance between the given addresses 
echo '<p>Distance: '.$distance.'</p>';

You can convert units and get the distance in a human-readable format (such as km, meter, etc.) using PHP:

// Distance in kilometer 
$distance_km round($miles 1.6093442).' km';

// Distance in meter
$distance_meter round($miles 1609.3442).' meters';

Get zipcode from address using Google Maps API and PHP

Conclusion

This simple distance calculator script will be very useful for getting the distance from addresses with PHP. You can easily calculate distance between two locations or coordinates using PHP. There are various geographic info will be available in Geocoding API’s response and you can use them for other purposes as needed.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

20 Comments

  1. Ynaps Said...
  2. Paul Said...
  3. Harshana Malshan Said...
  4. Fatih Said...
  5. Tamara Said...
  6. Emmanuel Said...
  7. Karthick Said...
  8. Mark Said...
  9. Carlos Gonzalez Said...
  10. Dave Said...
  11. Ghareeb Moahmed Said...
  12. Wazed Ali Said...
  13. Sahi Said...
  14. Rajakumaran Said...
  15. Chriso Said...
  16. Matthew Said...
    • CodexWorld Said...
  17. Ganesh Said...
  18. Boopathi Said...

Leave a reply

keyboard_double_arrow_up