2015-10-14 123 views
1

我有一个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> 
+0

有你'的var_dump( $ VAL)'? –

+0

您的邮编750341的谷歌搜索结果返回以下内容“{0​​”results“:[], ”status“:”ZERO_RESULTS“ }。所以如果谷歌没有回报,我认为我们无法操纵它。 – Dhay

+0

我测试了你的代码,我得到'Latitude:33.9697897 Longitude:-118.2468148'作为输出。 –

回答

0

我觉得你的问题是在API调用必须在HTTP因此改变httphttps

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