使用PHP从邮政编码获取纬度和经度


Get latitude and longitude from zip code using PHP

我有一个PHP页面,其中包含以下代码,用于从用户输入的邮政编码获取纬度和经度。

但是当我尝试回显纬度和经度时,什么也没有显示。

<?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>

请在api请求中添加关键参数。需要替换为google API Key的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'];
    }

我已经测试了你的代码,它的工作完美,我的猜测是你已经超过了你的Google Places API Web Service的每日配额。
一个快速的解决方案是申请key:

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

我认为你的问题是API调用必须在HTTP上,所以将http更改为https

<?php
    function getLnt($zip){
    $url = "https://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");
?>

不确定何时但在2019年,我们可以使用components in代替address以获得更准确的结果。例如:国家是美国,邮政编码是41000

$url = "https://maps.googleapis.com/maps/api/geocode/json?components=" . urlencode('country:US|postal_code:41000') . "&key=YOUR_API_KEY";
    function getLnt($zip){
    $url = "https://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($zip)."&sensor=false&key=YOUR_KEY";
    $result_string = file_get_contents($url);
    $result = json_decode($result_string, true);
    return $result['results'][0]['geometry']['location'];
    }
  print_r(getLnt("462021"));