2015-10-14 119 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"); 
?>