下面是我目前正在使用的代码,我在其中将地址传递给函数,Nominatim API 应该返回一个 JSON,我可以从中检索地址的纬度和经度。
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = 'http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1';
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
// get the important data
$lati = $resp['lat'];
$longi = $resp['lon'];
// put the data in the array
$data_arr = array();
array_push(
$data_arr,
$lati,
$longi
);
return $data_arr;
}
问题是我总是以内部服务器错误告终。我检查了日志,这不断重复:
[[DATE] America/New_York] PHP 注意: undefined index :在线 [...php] 中的标题 [...]
[[DATE] America/New_York] PHP 注意: undefined variable :在线 [...php] 中的区域 [...]
这可能是什么问题?是因为 New_York
中的 _
吗?我曾尝试使用 str_replace
将其与 +
交换,但这似乎不起作用并且仍然返回相同的错误。
此外,该 URL 工作正常,因为我已经通过 JavaScript 和手动对其进行了测试(尽管 {$address}
已替换为实际地址)。
非常感谢任何帮助,谢谢!
编辑
此问题现已修复。问题似乎是 Nominatim 无法获取某些值,因此返回错误
最佳答案
鉴于变量 title
和 area
不存在,您提到的错误似乎与您发布的代码无关。我可以为您发布的 geocode
功能提供一些帮助。
主要问题是 $url
字符串周围有单引号 - 这意味着 $address
没有注入(inject)到字符串中,请求是针对 lat/长的“$地址”。使用双引号解决了这个问题:
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
其次,响应包含一组数组(如果不是 limit
参数,则可能会出现多个结果)。因此,当从响应中获取详细信息时,请查看 $resp[0]
而不仅仅是 $resp
。
// get the important data
$lati = $resp[0]['lat'];
$longi = $resp[0]['lon'];
完整的,为了简单起见,在末尾有一些缩写的数组构建:
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
return array($resp[0]['lat'], $resp[0]['lon']);
}
一旦您对它的工作感到满意,我建议您为 http 请求和响应的解码/返回添加一些错误处理。
关于php - 如何通过 PHP 使用 Nominatim API 检索经纬度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44423767/