PHP注意:尝试获取非对象的属性(谷歌地图api功能)

时间:2016-07-03 09:15:06

标签: php google-maps-api-3 drupal

获取PHP通知'注意:尝试获取非对象的属性'从以下函数中使用Google Maps API查找两个邮政编码之间的距离(特别是'返回'代码行触发通知)

function findTheDistanceBetween($postcode_from, $postcode_to){

    // tidy up spaces
    $postcode_from      = str_replace(" ", "+", $postcode_from);
    $postcode_to        = str_replace(" ", "+", $postcode_to);

    // get JSON back from Google
    $json = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$postcode_from&destinations=$postcode_to&sensor=false&units=metric");

    // convert to a normal array
    $php_array = json_decode($json);

    // extract output and return it
    return $php_array->rows["0"]->elements["0"]->distance->value;

}

如果这有任何区别,这是drupal网站的一部分。

我也从同一回程线收到另一个通知:
注意:未定义的偏移量:在findTheDistanceBetween()

中为0

任何帮助非常感谢。

2 个答案:

答案 0 :(得分:1)

这可能是一种包含错误处理的方法

$maps_object = json_decode($json);
if (isset($maps_object->status)) {
    if ($maps_object->status == "OK") {
        // extract output and return it
        return $maps_object->rows[0]->elements[0]->distance->value;
    } else { 
        // adapt content to your error handling
        return 'json status: ' . $maps_object->status; 
    } 
} else {
    return 'could not obtain json';
}

答案 1 :(得分:0)

如何为您的调试替换/围绕 Noticed 语句:

if (isset($maps_object->rows[0]->elements[0]->distance->value)) {
    return $maps_object->rows[0]->elements[0]->distance->value;
} else {
    $error = "Error in: ". __FUNCTION__ ."() file:". __FILE__ ." line:". __LINE__ ."<br>\njson: $json<br>\n";
    echo $error;
    return $error;
}