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.
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.
Copy this API key for later use in the script on the Google Maps Geocoding API request.
The following example code shows the steps to get the distance between two addresses using Google Geocoding API and PHP.
$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.https://maps.googleapis.com/maps/api/geocode/json
) using the file_get_contents() method in PHP.
address
(from which you want to calculate distance) and key
parameters in the Geocoding API URL as a query string.geometry
object of API response.<?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($miles, 2).' 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.609344, 2).' km';
// Distance in meter
$distance_meter = round($miles * 1609.344, 2).' meters';
Get zipcode from address using Google Maps API and PHP
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
Hi, I implemented this code and its working fine. Thank you.
But the problem here is, I am not getting the correct distance calculated through this function compared to google map distance. May I know the reason. I cross checked the latitude and longitude of source and destination of Google maps. Your response would be helpful
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