我试图通过Google的Geocode API获取经度和经度。 $url
我使用输出正确的JSON,但我的脚本中的某些内容无法正常工作。它没有输出$lati
& $longi
个变量。请查看以下脚本:
PHP:
<?php
$address = 'Tempe AZ';
$address = urlencode($address);
$url = "https://maps.google.com/maps/api/geocode/json?sensor=false&address={$address}";
$resp_json = file_get_contents($url);
$resp = json_decode($resp_json, true);
if ($resp['status'] == 'OK') {
// get the important data
$lati = $resp['results'][0]['geometry']['location']['lat'];
$longi = $resp['results'][0]['geometry']['location']['lng'];
echo $lati;
echo $longi;
} else {
return false;
}
?>
答案 0 :(得分:0)
原来是一个代理问题。该主题帮助:Using proxy with file_get_contents
补充说:
$opts = array(
'http' => array(
'method' => "GET",
'header' => "Accept-language: en\r\n".
"Cookie: foo=bar\r\n",
'proxy' => 'tcp://proxy.proxy.com:8080',
)
);
$context = stream_context_create($opts);
// open the file using the HTTP headers set above
$file = file_get_contents($url, false, $context);
答案 1 :(得分:0)
你的脚本也适合我。也许你会收到一个错误的电话:
$resp_json = file_get_contents($url);
。
如果发生这种情况,你应该这样做:
$resp_json = @file_get_contents($url);
if ($resp_json === FALSE) {
///logic for exception
} else {
///do your logic hear
}
答案 2 :(得分:0)
我在Laravel文件/类的顶部引入了Guzzle http包:请使用GuzzleHttp \ Client;
然后,要获取一个地址并将其转换为lat和lng以使用PHP / Laravel和Google Maps API保存,我在save()方法中添加了以下代码:
// get latitude and longitude of address with Guzzle http package and Google Maps geocode API
$client = new Client(); // GuzzleHttp\Client
$baseURL = 'https://maps.googleapis.com/maps/api/geocode/json?address=';
$addressURL = urlencode(request('street')) . ',' . urlencode(request('city')) . ',' . urlencode(request('state')) . '&key=' . env('GOOGLE_MAPS_API_KEY');
$url = $baseURL . $addressURL;
$request = $client->request('GET', $url);
$response = $request->getBody()->getContents();
$response = json_decode($response);
$latitude = $response->results[0]->geometry->location->lat;
$longitude = $response->results[0]->geometry->location->lng;