The use of the geocoding process is to change the address into geographic coordinates. Therefore, the Google Maps Geocoding API offers an easy way to fetch geographic data from the address. Usually, We need Geocoding API to get the latitude and longitude of an address in the web application. Apart from this, You can use Google Maps Geocoding API for a lot of purposes linked to the Geocoding data.
The distance calculation is valuable when your web application works with the user’s location. So, you can calculate the distance among addresses using Google Maps API and PHP. In this tutorial, we will explain to you how to calculate the distance between two addresses with Google Maps Geocoding API using PHP.
To use the Google Maps Geocoding API, you only need to stipulate the API Key in your appeal. Before proceeding, create an API key on Google Cloud Platform Console for Geocoding API.
All the distance calculation code is gathered into a PHP function to make it reusable. The getDistance() function receives three parameters and calculates the distance between two addresses using Google Maps Geocoding API and PHP.
$addressFrom
– Staring point address. Required.$addressTo
– The endpoint address. Required.$unit
– Optional. You can specify your desired unit (K – kilometer, M – meters). But, the default unit is miles.
SEE ALSO: Add Custom Marker Icons to Google Map Dynamically from the Database with PHP and MySQL
Calculate Distance Between Two Address
The getDistance() function helps to get the distance between two addresses using PHP.
- Specify your Google Maps API key.
- Choose the new format of the addresses.
- Initiate the Geocoding API request and specify the output format and address to fetch the geographic data.
- Recover the latitude and longitude from the geodata.
- Calculate the distance between latitude and longitude.
- Change unit and return distance.
/** * @function getDistance() * Calculates the distance between two address * * @params * $addressFrom - Starting point * $addressTo - End point * $unit - Unit type * * @author Allsweb * @url https://www.allsweb.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.609344, 2).' km'; }elseif($unit == "M"){ return round($miles * 1609.344, 2).' meters'; }else{ return round($miles, 2).' miles'; } }
Call the getdistance () function and pass two addresses between which you want to calculate the distance.
$addressFrom = 'Insert start address'; $addressTo = 'Insert end address'; // Get distance in km $distance = getDistance($addressFrom, $addressTo, "K");
Also, read our previous blog- How to Capture Screenshot of Website from URL using PHP