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 address. 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 many 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.

To use the Google Maps Geocoding API, you need to specify the API Key in your request. Before getting started, generate an API key on Google Cloud Platform Console for Geocoding API.

How to Get Google Maps Geocoding API Key

All the distance calculation code is grouped into a PHP function to make it reusable. The getDistance() function accepts three parameters and calculates the distance between two address using Google Maps Geocoding API and PHP.

  • $addressFrom – Required. Staring point address.
  • $addressTo – Required. The endpoint address.
  • $unit – Optional. The default unit is miles, You can specify your desired unit (K – kilometer, M – meters).

Calculate Distance Between Address

The getDistance() function helps to get the distance between two address using PHP.

  • Specify your Google Maps API key.
  • Change the format of the addresses.
  • Initiate the Geocoding API request and specify the output format and address to fetch the geographic data.
  • Retrieve the latitude and longitude from the geodata.
  • Calculate the distance between latitude and longitude.
  • Convert unit and return distance.
/**
 * @function getDistance()
 * Calculates the distance between two address
 * 
 * @params
 * $addressFrom - Starting point
 * $addressTo - End point
 * $unit - Unit type
 * 
 * @author CodexWorld
 * @url https://www.codexworld.com
 *
 */
function getDistance($addressFrom$addressTo$unit ''){
    // Google API key
    $apiKey 'Your_Google_API_Key';
    
    // Change address format
    $formattedAddrFrom    str_replace(' ''+'$addressFrom);
    $formattedAddrTo     str_replace(' ''+'$addressTo);
    
    // Geocoding API request with start address
    $geocodeFrom file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddrFrom.'&sensor=false&key='.$apiKey);
    $outputFrom json_decode($geocodeFrom);
    if(!empty($outputFrom->error_message)){
        return $outputFrom->error_message;
    }
    
    // Geocoding API request with end address
    $geocodeTo file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddrTo.'&sensor=false&key='.$apiKey);
    $outputTo json_decode($geocodeTo);
    if(!empty($outputTo->error_message)){
        return $outputTo->error_message;
    }
    
    // Get latitude and longitude from the geodata
    $latitudeFrom    $outputFrom->results[0]->geometry->location->lat;
    $longitudeFrom    $outputFrom->results[0]->geometry->location->lng;
    $latitudeTo        $outputTo->results[0]->geometry->location->lat;
    $longitudeTo    $outputTo->results[0]->geometry->location->lng;
    
    // Calculate distance between latitude and longitude
    $theta    $longitudeFrom $longitudeTo;
    $dist    sin(deg2rad($latitudeFrom)) * sin(deg2rad($latitudeTo)) +  cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) * cos(deg2rad($theta));
    $dist    acos($dist);
    $dist    rad2deg($dist);
    $miles    $dist 60 1.1515;
    
    // Convert unit and return distance
    $unit strtoupper($unit);
    if($unit == "K"){
        return round($miles 1.6093442).' km';
    }elseif($unit == "M"){
        return round($miles 1609.3442).' meters';
    }else{
        return round($miles2).' miles';
    }
}

Call the getDistance() function and pass two addresses between from which you want to calculate distance.

$addressFrom 'Insert start address';
$addressTo   'Insert end address';

// Get distance in km
$distance getDistance($addressFrom$addressTo"K");

Get zipcode from address using Google Maps API and PHP

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

19 Comments

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

Leave a reply

keyboard_double_arrow_up