Today We are going to learn “Get Latitude and Longitude from ZIP Code using Google Maps API and PHP” this tutorial help in many project, i.e getting location on users address ZIP code.
For Pointing the exact location on Google Map it will always be a good idea to pass the latitude and longitude with Google Maps API. In this tutorial, you’ll know how to get latitude and longitude from ZIP code using Google Maps API in PHP.
Get Location
<?php if(isset($_POST['submit'])) { $zipcode=$_POST['location']; $url = "http://maps.googleapis.com/maps/api/geocode/json?address=".$zipcode."&sensor=false"; $details=file_get_contents($url); $result = json_decode($details,true); $lat=$result['results'][0]['geometry']['location']['lat']; $lng=$result['results'][0]['geometry']['location']['lng']; echo "Latitude :" .$lat; echo '<br>'; echo "Longitude :" .$lng; } ?>
Front End Design
<!Doctype html> <html> <head> <title>Location|techJunkGigs</title> </head> <body> <form method = "POST" action = ""> <Label>Enter Your ZIP Code</Label> <Input type = "text" name = "location"> <input type = "submit" name = "submit" value = "Get Location"> </form> </body> </html>
Combine Code For Getting Longitude and Latitude
<!Doctype html> <html> <head> <title>Location|techJunkGigs</title> </head> <body> <form method = "POST" action = ""> <Label>Enter Your ZIP Code</Label> <Input type = "text" name = "location"> <input type = "submit" name = "submit" value = "Get Location"> </form> </body> </html> <?php if(isset($_POST['submit'])) { $zipcode=$_POST['location']; $url = "http://maps.googleapis.com/maps/api/geocode/json?address=".$zipcode."&sensor=false"; $details=file_get_contents($url); $result = json_decode($details,true); $lat=$result['results'][0]['geometry']['location']['lat']; $lng=$result['results'][0]['geometry']['location']['lng']; echo "Latitude :" .$lat; echo '<br>'; echo "Longitude :" .$lng; } ?>
Demo Image
So that’s all for this “Get Latitude and Longitude from ZIP Code using Google Maps API and PHP” tutorial friends. We learned how to run get longitude and latitude with ZIP code . if you found it helpful then, please SHARE. Thank You
Craftdecode says
Awesome Post. thanks for the awesome post with code
Jamaley Hussain says
Hi CraftDecode
I’m glad that you like it.
Thank you for stopping and commenting here keep visiting.
kix says
I get the message, when I try to execute the zip code: 21240
Notice: Undefined offset: 0 in C:\xampp\htdocs\myfiles\loc.php on line 23
Notice: Undefined offset: 0 in C:\xampp\htdocs\myfiles\loc.php on line 25
Latitude :
Longitude :
I got it working. You have to use your Google/gmail account to generate an API key (search on Google how to do this) and then manually enable Geocoding API in your account profile. Then the url link in the PHP file needs to be set to:
$url = “https://maps.googleapis.com/maps/api/geocode/json?address=”.$zipcode.”&key=YOUR_39_DIGIT_KEY”;
Key may not necessarily be 39 digits long, though.