Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get latitude and longitude from zip code using PHP

Tags:

php

google-api

I have a PHP page containing the following code to get latitude and longitude from a user input postal code.

But when I tried to echo the latitude and longitude, nothing is shown.

<?php
    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);
    return $result['results'][0]['geometry']['location'];
    }

    getLnt("750341");
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <?php
         $val = getLnt('90001');
         echo "Latitude: ".$val['lat']."<br>";
         echo "Longitude: ".$val['lng']."<br>";
        ?>
    </body>
</html>
like image 248
beny lim Avatar asked Jul 09 '26 05:07

beny lim


2 Answers

Please add key parameter in api request. Key value you need to replace with google API key.

$url = "https://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($postal_code)."&sensor=false&key=googleapi";
    $result_string = file_get_contents($url);
    $result = json_decode($result_string, true);
    if(!empty($result['results'])){
        $zipLat = $result['results'][0]['geometry']['location']['lat'];
        $ziplng = $result['results'][0]['geometry']['location']['lng'];
    }
like image 143
sohan verma Avatar answered Jul 11 '26 20:07

sohan verma


I've tested your code and it works perfectly, my guess is that you've exceeded your daily quota for the Google Places API Web Service.
A quick solution is to apply for a key at:

https://console.developers.google.com/

like image 22
Pedro Lobito Avatar answered Jul 11 '26 21:07

Pedro Lobito