In this article, you are going to learn that, how to create a distance calculator sort of module which can find distance between two addresses. We are going to use google map API and PHP to accomplish this task.
The distance calculator module we are going to develop here is basically an API provided by The Google itself. This API can measure the driving distance between two location as well as Travel Time. You can also measure distance between cities using this module.
The format for origin location and destination location could be one of the following:
- place name (e.g. Bhopal, India)
- ZIP code (e.g. 462016)
- latitude/longitude coordinates (e.g. 23.77xxx, 77.30xxx)
to know more about permissible formats please visit Google’s official documentation page.
Find Distance Between two Addresses
Step 1:- Get a google’s API Key from https://developers.google.com/maps/documentation/distance-matrix/get-api-key.
click on GET A KEY button
now click on +create a new project
and enter your project name then click on ENABLE API
button
then after you are finally prompted to a popup window containing your API KEY
.
Step 2: source code
<!DOCTYPE html>
<html>
<body>
<form action="" method="post">
<label>Origin:</label> <input type="text" name="o" placeholder="Enter Origin location" required> <br><br>
<label>Destination:</label> <input type="text" name="d" placeholder="Enter Destination location" required> <br><br>
<input type="submit" value="Calculate distance & time" name="submit"> <br><br>
</form>
<?php
if(isset($_POST['submit'])){
$origin = $_POST['o']; $destination = $_POST['d'];
$api = file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=".$origin."&destinations=".$destination."&key=YOUR_API_KEY");
$data = json_decode($api);
?>
<label><b>Distance: </b></label> <span><?php echo ((int)$data->rows[0]->elements[0]->distance->value / 1000).' Km'; ?></span> <br><br>
<label><b>Travel Time: </b></label> <span><?php echo $data->rows[0]->elements[0]->duration->text; ?></span>
<?php } ?>
</body>
</html>
replace YOUR_API_KEY
with your API KEY (Step 1) in above code.
We have covered find distance between two addresses module in this article, to get latest updates please subscribe our blog and follow us on Facebook. Don’t forget to share this article with your friends.
You may also like
Please help us by showing your reaction
Well great information paritosh. explained in detail. Thanks for sharing.
Thank you for your valuable response Mr. Harris.
Very good explaining and clean code, well done. I wish you could consider some demo preview…
Keep us posted…
Thank you @Christos for appreciating, and sure I’m definitely gonna implement your suggestion.
Hey just wanted to give you a quick heads up. The words in your article seem
to be running off the screen in Safari. I’m not sure if this is
a format issue or something to do with browser compatibility but I thought I’d post to let you
know. The design look great though! Hope you get the problem solved soon. Many thanks
Nice, but is there a way to get suggestion when you type the address? For instance if you type Paris to see: Paris, France, Paris Museum….?
you should go ahead and should take a look at the demo, actually it do have this suggestion feature already.
Thanks for your demo, actually auto-suggestion its not working, maybe because not https?
yeah sorry its my bad, here is autocomplete address search module
https://www.myprogrammingtutorials.com/autocomplete-address-search-module-google-api-php.html
That was a great explanation, I have to develop such kind of application in my website. Thanks alot for sharing.
Hello @Vinay,
Thanks for appreciating man and keep visiting.
Notice: Undefined offset: 0 in C:\xampp\htdocs\bus\api.php on line 19
Notice: Trying to get property ‘elements’ of non-object in C:\xampp\htdocs\bus\api.php on line 19
Notice: Trying to get property ‘distance’ of non-object in C:\xampp\htdocs\bus\api.php on line 19
Notice: Trying to get property ‘value’ of non-object in C:\xampp\htdocs\bus\api.php on line 19
0 Km
#error of ur code
Hello @tahir,
its my bad I’ve not used exceptions.
please print the
$api
variable, I think it is not returning the required response.maybe it is because of providing an invalid
API_KEY
.can you explain a little bit more please
I am copied your code carefully but it’s not working
what error exactly you’re getting, please try to share that errors, so that I can help you out.
I am getting these errors while running your code. How to solve this?
Notice: Undefined offset: 0 in C:\xampp\htdocs\bus\api.php on line 19
Notice: Trying to get property ‘elements’ of non-object in C:\xampp\htdocs\bus\api.php on line 19
Notice: Trying to get property ‘distance’ of non-object in C:\xampp\htdocs\bus\api.php on line 19
Notice: Trying to get property ‘value’ of non-object in C:\xampp\htdocs\bus\api.php on line 19
0 Km
Thank you so much for this! You saved me a while of research/”reverse-engineering” the API
Best regards
glad to help you @Tip
Hi,
Thanks for the code
But I can’t make it working even on the demo page.
I try few adress and gps coordinate on your demo page but it always return 0 km.
Does your demo page still working ?
Thankss
Distance: rows[0]->elements[0]->distance->value / 1000).’ Km’; ?>
Travel Time: rows[0]->elements[0]->duration->text; ?>
Sorry, please help me
you’ve not used
$data
variableWarning: file_get_contents(https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Jakarta, Indonesia&destinations=Bandung, Indonesia&key=AIzaSyBZG1funcpMjPtXCHBMVvSXOpKw-cBP6Xg): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in C:\xampp\htdocs\bu\ta2.php on line 17
as per your URL provided above I find there a white space between akarta, & Indonesia
you need to
urlencode()
your URLas you can see bellow URL is working fine
https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Jakarta,%20Indonesia&destinations=Bandung,%20Indonesia&key=AIzaSyBZG1funcpMjPtXCHBMVvSXOpKw-cBP6Xg
Oh, thank you very much.
Can i get real time data (with current traffic) ?
I guess so!
I think you just need to grab your current coordinates (lat, lang) using GPS every time (you can use loop) and convert them into an address (you can use any third party API).
so here the destination would be a static address and origin would be a dynamic address.
oh, no need. i have got it
Thank you very much
Oh can you please let us know how you fix it?
Okay, just use direction and departure time
Dear,
First of all thanks a lot for your post.
I try to your code and it working, but have a problem. problem is when i add to API, 1st time it’s working but not working 2nd time. so what can i do now. I am a student. it’s my University project. please help me.
hello sir i am use you code.
please help me how to find free google API KEY i have no idea about API because i am a student
please help me. please reply as soon as possible
Google has changed their API’s pricing plans, even though anyone can use their API for free as well.
You have to enable billing first, when you enable billing, you get $200 free usage every month for Maps, Routes, or Places(please refer google’s official page for more info).
I think $200 would be more than enough for an any Individuals.
hello sir,
i want to aad price in your code
please share code.
regards,
santosh yadav
Hi,
Thank you for your code. Actually it does not seem to work for me. I have copied all the code form article and I’ve added my api. All I can see after the refresh is:
Origin: [input]
Destination: [input]
Distance: rows[0]->elements[0]->distance->value / 1000).’ Km’; ?>
Travel Time: rows[0]->elements[0]->duration->text; ?>
Thanks a lot
Thanks so much for this, the demo still works but when I use the same code on a test page with my own API key, I always get 0km as the result and no travel time. What could be the problem?
In Google I can see my calls are being received by the API. I am trying Melbourne to Sydney, which comes up with results in your demo but not mine…
Thanks Dear bro…….for doing such a help.
yor demo is not working it give me 0 KM distance
Hai
I am beginner level in php. May i know how to implement to calculation distance by state wise mileage and insert fetch data in mysql db:
For eg:
From Input field : columbus
To Input Field : Miami
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
Waiting for you help
you can search state wise as well with this module, see demo link(updated) https://demo.myprogrammingtutorials.com/find-distance-between-two-addresses-google-api-php/
I facing some problem please help me the api key give the problem
util.js:230 Google Maps JavaScript API warning: NoApiKeys https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys
pz.o @ util.js:230
util.js:230 Google Maps JavaScript API warning: SensorNotRequired https://developers.google.com/maps/documentation/javascript/error-messages#sensor-not-required
your information is helpful, thankyou
Distance:
Notice: Undefined offset: 0 in C:\xampp\htdocs\cal\distance.php on line 21
Notice: Trying to get property ‘elements’ of non-object in C:\xampp\htdocs\cal\distance.php on line 21
Notice: Trying to get property ‘distance’ of non-object in C:\xampp\htdocs\cal\distance.php on line 21
Notice: Trying to get property ‘value’ of non-object in C:\xampp\htdocs\cal\distance.php on line 21
0 Km
Travel Time:
Notice: Undefined offset: 0 in C:\xampp\htdocs\cal\distance.php on line 22
Notice: Trying to get property ‘elements’ of non-object in C:\xampp\htdocs\cal\distance.php on line 22
Notice: Trying to get property ‘duration’ of non-object in C:\xampp\htdocs\cal\distance.php on line 22
Notice: Trying to get property ‘text’ of non-object in C:\xampp\htdocs\cal\distance.php on line 22
i am getting this error
Hello Shrutik,
it seems
$data
variable is not getting populated as we need, could you please shareprint_r($data);
data?