Distance between two addresses using Google Maps API and PHP


We can easily calculate distance between two addresses using Google Maps API and PHP. We have created a simple PHP function for getting distance between two addresses. getDistance() function grouped all functionalities together and it accepts three parameters.

  • $addressFrom – Required. Pass the from address.
  • $addressTo – Required. Pass the to address.
  • $unit – Optional. Pass the first letter of desire unit. Default is Mile. ( K – kilometre, N – Nautical Mile)

getDistance() function is given below.

/**
*
* Author: CodexWorld
* Function Name: getDistance()
* $addressFrom => From address.
* $addressTo => To address.
* $unit => Unit type.
*
**/
function getDistance($addressFrom$addressTo$unit){
    
//Change address format
    
$formattedAddrFrom str_replace(' ','+',$addressFrom);
    
$formattedAddrTo str_replace(' ','+',$addressTo);
    
    
//Send request and receive json data
    
$geocodeFrom file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$formattedAddrFrom.'&sensor=false');
    
$outputFrom json_decode($geocodeFrom);
    
$geocodeTo file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$formattedAddrTo.'&sensor=false');
    
$outputTo json_decode($geocodeTo);
    
    
//Get latitude and longitude from geo data
    
$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 from 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;
    
$unit strtoupper($unit);
    if (
$unit == "K") {
        return (
$miles 1.609344).' km';
    } else if (
$unit == "N") {
        return (
$miles 0.8684).' nm';
    } else {
        return 
$miles.' mi';
    }
}

You can use this function like the below.

$addressFrom 'Insert from address';
$addressTo 'Insert to address';
$distance getDistance($addressFrom$addressTo"K");
echo 
$distance;

To specify a Google API key in your request, include it as the value of a key parameter.

$geocode file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$formattedAddr.'&sensor=false&key=GoogleAPIKey');

6 Comments

  1. Rajakumaran Said...
  2. Chriso Said...
  3. Matthew Said...
    • CodexWorld Said...
  4. Ganesh Said...
  5. Boopathi Said...

Leave a reply

Connect With CodexWorld