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

3
我有一个包含以下代码的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>

你有执行过 var_dump($val) 吗? - u_mulder
你的邮政编码750341在谷歌上的搜索结果返回了以下内容 { "results" : [], "status" : "ZERO_RESULTS" }。所以如果谷歌没有返回任何结果,我认为我们无法对其进行操作。 - Dhay
我已经测试了你的代码,输出结果为 纬度:33.9697897,经度:-118.2468148 - Pedro Lobito
1
$result_string = file_get_contents($url); 之后立即执行 var_dump($result_string);,它显示了什么? - Pedro Lobito
1
你得到了你的答案 :) - Pedro Lobito
显示剩余8条评论
5个回答

3
请在API请求中添加关键参数。您需要使用Google API密钥替换密钥值。
$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'];
    }

2

1
我认为你的问题在于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");
?>

1
在2019年的某个时间点,我们可以使用components代替address来获得更准确的结果。例如:国家是美国,邮政编码是41000。
$url = "https://maps.googleapis.com/maps/api/geocode/json?components=" . urlencode('country:US|postal_code:41000') . "&key=YOUR_API_KEY";


0
    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"));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接