在我的一个php应用程序中,我必须从地址中找出该地点的纬度和经度。
我试过这段代码:
$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false®ion=$region");
$json = json_decode($json);
$lat = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
$long = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
但它显示以下错误:
警告:file_get_contents(http://maps.google.com/maps/api/geocode/json?address=technopark,Trivandrun,喀拉拉邦,印度& sensor = false& region = IND)[function.file-get-内容]:无法打开流:HTTP请求失败!第4行的D:\ Projects \ lon.php中的HTTP / 1.0 400错误请求
请帮我解决这个问题。
答案 0 :(得分:39)
使用curl
代替file_get_contents
:
$address = "India+Panchkula";
$url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false®ion=India";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_a = json_decode($response);
echo $lat = $response_a->results[0]->geometry->location->lat;
echo "<br />";
echo $long = $response_a->results[0]->geometry->location->lng;
答案 1 :(得分:37)
$address = str_replace(" ", "+", $address);
在file_get_content之前使用上面的代码。 意思是,使用以下代码
$address = str_replace(" ", "+", $address);
$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false®ion=$region");
$json = json_decode($json);
$lat = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
$long = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
它肯定会有效。 由于地址不支持空格,因此它仅支持+符号代替空格。
答案 2 :(得分:8)
//add urlencode to your address $address = urlencode("technopark, Trivandrun, kerala,India"); $region = "IND"; $json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false®ion=$region"); echo $json; $decoded = json_decode($json); print_r($decoded);
答案 3 :(得分:4)
两个想法:
答案 4 :(得分:1)
$address = str_replace(" ", "+", $address);
$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false®ion=$region");
$json = json_decode($json);
$lat = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
$long = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
答案 5 :(得分:0)
...别忘了&#34; $ region&#34;使代码工作:
$address = "Salzburg";
$address = str_replace(" ", "+", $address);
$region = "Austria";
$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false®ion=$region");
$json = json_decode($json);
$lat = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
$long = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
echo $lat."</br>".$long;
答案 6 :(得分:0)
我认为您的apache服务器上的 allow_url_fopen 已被禁用。您需要将其运行。
将 allow_url_fopen = 0 更改为 allow_url_fopen = 1
别忘了更改它后重新启动Apache服务器。