这是一个我正在尝试运行的简单代码,但它没有输出任何数据。有人可以帮忙吗?谢谢!
<?php
$addr = "Hotels in ottawa canada";
$a = urlencode($addr);
$geocodeURL =
"https://maps.googleapis.com/maps/api/geocode/json?address=$a&sensor=false&key=my key";
$ch = curl_multi_init($geocodeURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_multi_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$geocode = json_decode($result);
$lat = $geocode->results[$i]->geometry->location->lat;
$lng = $geocode->results[$i]->geometry->location->lng;
echo $formatted_address = $geocode->results[$i]->formatted_address;
echo $geo_status = $geocode->status;
echo $location_type = $geocode->results[0]->geometry->location_type;
echo $location_type = $geocode->results[$i]->geometry->premise;
echo $street_address = $geocode->results[$i]->street_address;
?>
答案 0 :(得分:0)
如果您希望将多个地址并行传递给google api,然后将结果解析为一个,我会整理一个小例子并修复您的curl多代码。希望它有所帮助。
<?php
$urls = array(
'http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true',
'http://maps.googleapis.com/maps/api/geocode/json?address='.urlencode('Hotels').'&sensor=true');
$response = curl_get_multi($urls);
//Handle response array
foreach($response as $json){
$result = json_decode($json);
//echo $result->status.' ';
//Iterate each result
foreach($result->results as $res){
//lat
echo $res->geometry->location->lat.' ';
//lng
echo $res->geometry->location->lng.' ';
//formatted_address
echo $res->formatted_address.' ';
//location_type
echo $res->geometry->location_type.' ';
echo '<br/>';
}
echo '<hr />';
}
/**
* Curl multi function
*
* @param Array $urls
* @return Array
*/
function curl_get_multi($urls) {
$curly = array();
$result = array();
$mh = curl_multi_init();
foreach ($urls as $id=>$url) {
$curly[$id] = curl_init();
curl_setopt($curly[$id], CURLOPT_URL, $url);
curl_setopt($curly[$id], CURLOPT_HEADER, 0);
curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, true);
curl_setopt($curly[$id], CURLOPT_TIMEOUT, 2);
curl_setopt($curly[$id], CURLOPT_USERAGENT, 'CurlRequest');
curl_setopt($curly[$id], CURLOPT_REFERER, $url);
curl_setopt($curly[$id], CURLOPT_AUTOREFERER, true);
curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $curly[$id]);
}
$running = null;
do {
curl_multi_exec($mh, $running);
} while($running > 0);
foreach($curly as $id => $c) {
$result[$id] = curl_multi_getcontent($c);
curl_multi_remove_handle($mh, $c);
}
curl_multi_close($mh);
return $result;
}
?>