3

下面是我当前使用的代码,我在其中将地址传递给函数,并且 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 Notice: Undefined index: title in [...php] on line [...]

[[DATE] America/New_York] PHP Notice: Undefined variable: area in [...php] on line [...]

这里可能是什么问题?是因为_New_York吗?我曾尝试将str_replace其与 a 交换,+但这似乎不起作用,并且仍然返回相同的错误。

此外,该 URL 工作正常,因为我已通过 JavaScript 和手动对其进行了测试(尽管{$address}已替换为实际地址)。

非常感谢您对此的任何帮助,谢谢!

编辑

现在已解决此问题。问题似乎是 Nominatim 无法获取某些值,因此返回错误

4

1 回答 1

5

您提到的错误似乎与您在给定变量的情况下发布的代码无关title,并且area不存在。geocode我可以为您发布的功能提供一些帮助。

主要问题是字符串周围有单引号$url- 这意味着$address没有注入字符串并且请求是针对“$address”的纬度/经度。使用双引号可解决此问题:

$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 请求和响应的解码/返回添加一些错误处理。

于 2017-06-08T02:46:23.750 回答