[英]Reverse geocoding using Nominatim in PHP
我試圖在PHP中執行一些反向地理編碼。 不幸的是,我收到了一個錯誤。
$lon = 100.753;
$lat = 13.69362;
function getAddress($RG_Lat,$RG_Lon)
{
$json = "http://nominatim.openstreetmap.org/reverse?format=json&lat=".$RG_Lat."&lon=".$RG_Lon."&zoom=27&addressdetails=1";
$jsonfile = file_get_contents($json);
$RG_array = json_decode($jsonfile,true);
foreach ($RG_array as $name => $value)
{
if($name == "display_name")
{
$RG_address = $value;
break;
}
}
return $RG_address;
}
$addr = getAddress($lat,$lon);
echo "Address: ".$addr;
以下是我得到的錯誤。
<b>Warning</b>: file_get_contents(http://nominatim.openstreetmap.org/reverse?format=json&lat=13.69362&lon=100.753&zoom=27&addressdetails=1): failed to open stream: Connection timed out in <b>/home/public_html/myapp/get_loc.php</b> on line <b>22</b><br />
<br />
<b>Warning</b>: Invalid argument supplied for foreach() in <b>/home/public_html/myapp/get_loc.php</b> on line <b>25</b><br />
<br />
<b>Notice</b>: Undefined variable: RG_address in <b>/home/public_html/myapp/get_loc.php</b> on line <b>34</b><br />
Address: <br />
如果我在Angular中使用下面的代碼,那么它工作正常。
showCountry($scope.latitude,$scope.longitude);
function showCountry(lat, lon) {
$.getJSON('//nominatim.openstreetmap.org/reverse?json_callback=?&format=json', {lat: lat, lon: lon}, function(data) {
console.log(data.address.town);
console.log('suburb- '+data.address.suburb);
console.log('county/district -'+data.address.county);
console.log('state - '+data.address.state);
console.log(data.address.postcode);
console.log(data.address.country);
});
}
我無法在客戶端執行此操作; 這就是我需要在php中完成它的原因。
您應該使用cURL (而不是file_get_contents()
)向服務器請求用戶代理標頭,因為OSM僅接受具有有效用戶代理的請求:
$lon = 100.753;
$lat = 13.69362;
function getAddress($RG_Lat,$RG_Lon)
{
$json = "https://nominatim.openstreetmap.org/reverse?format=json&lat=".$RG_Lat."&lon=".$RG_Lon."&zoom=27&addressdetails=1";
$ch = curl_init($json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0");
$jsonfile = curl_exec($ch);
curl_close($ch);
$RG_array = json_decode($jsonfile,true);
return $RG_array['display_name'];
// $RG_array['address']['city'];
// $RG_array['address']['country'];
}
$addr = getAddress($lat,$lon);
echo "Address: ".$addr;
輸出:
地址:短期停車場,Sky Lane,สมุทรปราการ,จังหวัดสมุทรปราการ,10520,ประเทศไทย
另外,正如@Kevin_Kinsey指出的那樣,您還可以將file_get_contents()
與stream_context_create()
:
$opts = [
'http' => [
'method'=>"GET",
'header'=>"User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:59.0) \r\n"
]
];
$context = stream_context_create($opts);
$jsonfile = file_get_contents($json, false, $context);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.