Get latitude and longitude from zip code using PHP

The following PHP function will generate Latitude and Longitude from given zip code.

function getLnt($zip){
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=
".urlencode($zip)."&sensor=false";
$result_string = file_get_contents($url);
$result = json_decode($result_string, true);
$result1[]=$result['results'][0];
$result2[]=$result1[0]['geometry'];
$result3[]=$result2[0]['location'];
return $result3[0];
}

To display output:
<?php
 $val = getLnt('90001');
 echo "Latitude: ".$val['lat']."<br>";
 echo "Longitude: ".$val['lng']."<br>";
?>

In Action:
Enter Zip code

 

Comments
28 February
2014
Nilesh
Hi There,

Could you tell me how to get zip code from lat long?
03 December
2013
Eric Jackman
if you rewrite

$result1[]=$result['results'][0];
$result2[]=$result1[0]['geometry'];
$result3[]=$result2[0]['location'];
return $result3[0];

as

return $result['results'][0]['geometry']['location'];

you will speed up your script and not eat up as much memory
01 January
2014
Hodgetts
Thanks a bunch for sharing this with all folks you really recognize what you are
talking about! Bookmarked. Please additionally discuss with my web site =).
We could have a link trade agreement between us

Look into my weblog: car insurance quotes
06 October
2013
philip
hi i would like to let people type in a zip code and search people within a certain radius of that zip code how can i do that i am also new to php so please be specific
28 August
2013
glw
im new to PHP. is the second section is what goes inside my webpage?if so, does it go in the ?

29 August
2013
Rishi
Yes, The First Section is the Function and write the second part in your page where you want to display the result.
comments powered by Disqus