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).The getDistance() function helps to get the distance between two address using PHP.
/** * @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.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 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
Has anyone managed to apapt this to show Driving distance rather than point to point?
This was very helpful. Thank you and wish you all the best for do more great things.
It worked at a difficult time. thanks
Hi,
How would I make this work with the Google Maps distance matrix, to get a driving distance instead of a straight line?
Thanks
Please can you provide a tutorial to calculate the driving distance in PHP like the above?.
Please i will so much appreciate this, as my ongoing project really needs this functionality and have never worked on Google Map in the past.
hai
how to implement php function to show total distance in miles by state wise mileage calculation like below
for eg
input field from location
input field destination location
Summary
From: Columbus, OH, USA
To: Miami, FL, USA
Duration: 17 hours 8 mins
State Distance (miles)
OH 113.3
WV 146.85
VA 71.25
NC 107.04
SC 228.05
GA 112.76
FL 376.12
Total 1155.38
i already done it in javascript function..but i am beginner level in php how to do this.
thanks
by
karthick
Sahi Said…
this show only distance from point to point, what about driving distance?
April 18, 2017 at 1:17 PM
I have the same question. Can anybody help me/us with that?
Thanks a lot! work like charm, at first run.
Sad, every set of addresses I input comes back as 0 distance! 🙁
This issue occurred because of the new Geocoding API Usage and Billing policy. Please see the details from here – https://developers.google.com/maps/documentation/geocoding/usage-and-billing
thank you for your Code
i want this code for codeigniter framework please
Thank you …
Was a great help. Thank you so much.
this show only distance from point to point, what about driving distance?
Easy to Understand Thank You So MUch
I love this, thanks so much!
Trouble I’m having is I am using it in a loop to find the lowest distance between points and it can be quite slow.
I’ve already filtered my array to match the state I’m in and added a high threshold to exit if distance < x.
Any other ideas on how I might speed up this function?
Cheers!
I can’t seem to figure this out… Do I need to use an API key? Or should it work without it?? It doesn’t show up as anything at the moment.
@Matthew You can call the Google Geocode API without specifying any API key. But there has a daily request quota, once the daily limit is exceeded you would not get any result. So, it would be a good idea to use your Google API Key.
Thanks ,you saved my life !
Nice