使用php、API自动获取经度和纬度


Get latitude and longitude automatically using php, API

在我的一个php应用程序中,我必须从地址中找出这个地方的经纬度。

我试过这个代码:

$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$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,喀拉拉邦,India&传感器= false&地区=印第安纳州)[功能。file-get-contents]: failed to open stream: HTTP请求失败!HTTP/1.0 400错误请求在D:'Projects' long .php on line 4

请帮我解决这个问题

curl代替file_get_contents:

$address = "India+Panchkula";
$url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=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;
$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&region=$region");
$json = json_decode($json);
$lat = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
$long = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};

,它一定会起作用。由于address不支持空格,它只支持+号来代替空格。

//添加urlencode到您的地址美元地址= urlencode("科技园,Trivandrun,喀拉拉邦,印度");$region = "IND";$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region");echo $ json;$decoded = json_decode($json);print_r(解码);

两个想法:

  • 地址和地区URL是否编码?
  • 也许你的计算机运行的代码不允许http访问。尝试加载另一个页面(如'http://www.google.com'),看看是否有效。如果这也不起作用,那么PHP设置有问题。
$address = str_replace(" ", "+", $address);
$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region");
$json = json_decode($json);
$lat = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
$long = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};

…不要忘记使用$region来让代码工作:

$address = "Salzburg";
$address = str_replace(" ", "+", $address);
$region = "Austria";
$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region");
$json = json_decode($json);
$lat = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
$long = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
echo $lat."</br>".$long;

我认为allow_url_fopen在您的apache服务器上是禁用的。你得把它打开

请将allow_url_fopen = 0改为allow_url_fopen = 1