使用javascript获取当前的lat和lng没问题。但我想通过file_get_contents在PHP中调用API链接,如下所示:
<?php
$json = file_get_contents('https://www.googleapis.com/geolocation/v1/geolocate?key=Jsddds6s6sdht43asdsaASasta8962');
?>
目前,如果我在Chrome中粘贴网址,则会收到 Not Found 。为什么会这样?
答案 0 :(得分:2)
由于您正在使用查询字符串GET方法
,因此给出错误 使用POST方法检索数据,因为Google地理位置只允许发布方法
这是一个例子
<!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({
type : 'POST',
data: '',
url: "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCW0lvagDP67ulkwwP7yAIBHJoj2HT0apM",
success: function(result){
$('#lat').html(result['location']['lat']);
$('#lng').html(result['location']['lng']);
}});
});
} );
</script>
</body>
</html>
&#13;
答案 1 :(得分: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');
}
或者,您可以尝试使用它 -
$str = file_get_contents('https://www.googleapis.com/geolocation/v1/geolocate?key=Jsddds6s6sdht43asdsaASasta8962');
$json = json_decode($str, true);
所以这应该给你一个json字符串,然后你可以通过解码来操作它。