2016-09-15 325 views
-1

使用javascript獲取當前的緯度和經度我沒有問題。但我想通過打電話的file_get_contents在PHP中的API鏈接如下:從Google地理定位API獲取當前經緯度和lng

<?php 
$json = file_get_contents('https://www.googleapis.com/geolocation/v1/geolocate?key=Jsddds6s6sdht43asdsaASasta8962'); 
?> 

當前,如果我貼在Chrome的網址,我得到未找到。爲什麼發生這種情況?

回答

1

它給錯誤,因爲你在使用查詢字符串GET方法,它

使用POST方法來檢索數據,因爲谷歌的地理定位只允許POST方法 enter image description here 這裏有一個例子

<!DOCTYPE html> 
 
<html lang="en"> 
 
<head> 
 
    <title>Geocode Example</title> 
 
    <meta charset="utf-8"> 
 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
 
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> 
 
    
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
 
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
 
    
 
</head> 
 
<body> 
 
<span>Your Latitude : </span><span id="lat"></span><br> 
 
<span>Your Longitude : </span><span id="lng"></span><br> 
 
<button id="btn">Click Here To Get Lat And Lng</button> 
 
<script> 
 
$(document).ready(function() { 
 
    $('#btn').click(function(e) { 
 
     $.ajax({ 
 
\t \t type : 'POST', 
 
\t \t data: '', 
 
\t \t url: "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCW0lvagDP67ulkwwP7yAIBHJoj2HT0apM", 
 
\t \t success: function(result){ 
 
     \t \t $('#lat').html(result['location']['lat']); 
 
\t \t \t \t $('#lng').html(result['location']['lng']); 
 
\t \t \t \t \t 
 
    \t \t }}); 
 
\t \t \t \t \t 
 
    }); 
 
}); 
 
</script> 
 

 
</body> 
 
</html>

+0

謝謝你指出這一點。通常我們會忽略最簡單的通知。 –

0

第一步是檢查您從API獲得的響應。

function get_http_response_code($url) { 
    $headers = get_headers($url); 
    return substr($headers[0], 9, 3); 
} 
if(get_http_response_code('https://www.googleapis.com/geolocation/v1/geolocate?key=Jsddds6s6sdht43asdsaASasta8962') != "200"){ 
    echo "Error parsing api"; 
}else{ 
    file_get_contents('https://www.googleapis.com/geolocation/v1/geolocate?key=Jsddds6s6sdht43asdsaASasta8962'); 
} 

參考Dev Guid for Response

或者,您可以嘗試使用此 -

$str = file_get_contents('https://www.googleapis.com/geolocation/v1/geolocate?key=Jsddds6s6sdht43asdsaASasta8962'); 
$json = json_decode($str, true); 

因此,這應該給你一個JSON字符串,然後你可以通過解碼操作它。

+0

我知道它給了我錯誤,因爲我直接在地址欄中粘貼了URL。我之所以這樣做的原因之一是因爲我不希望編碼javascript :( –

+0

已更新我的回答 – Techidiot

相關問題