检查键是否存在于面向对象的编程中

时间:2019-03-03 02:14:35

标签: php json google-maps object geocoding

有时会丢失来自Google API查询的数据(例如,当输入无效地址时),并且这种情况发生时,会出现丑陋的未知密钥错误。为了避免出现丑陋的错误,我将调用包装成一个有条件的调用,但似乎根本无法使其正常工作,因为我不存在面向对象的编程技能。以下是我所拥有的以及一些已指出的尝试,所以我在做什么错?我真的很在乎 $ dataset-> results [0] 是否有效,因为之后的任何事情都是有效的。

$url = "https://maps.googleapis.com/maps/api/geocode/json?address=$Address&key=$googlekey";

// Retrieve the URL contents
$c = curl_init();
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_FRESH_CONNECT, true);
curl_setopt($c, CURLOPT_URL, $url);
$jsonResponse = curl_exec($c);
curl_close($c);    

$dataset = json_decode($jsonResponse);

if (isset($dataset->results[0])) :
//if (isset($dataset->results[0]->geometry->location)) :
//if (!empty($dataset)) :
//if (!empty($dataset) && json_last_error() === 0) :
    $insertedVal = 1;
    $latitude = $dataset->results[0]->geometry->location->lat;
    $longitude = $dataset->results[0]->geometry->location->lng;
    return "$latitude,$longitude";
endif;

1 个答案:

答案 0 :(得分:1)

您应该注意,Geocoding API网络服务还会在响应中返回状态。状态指示响应中是否包含有效项目,或者出了什么问题而您没有任何结果。

看看文档https://developers.google.com/maps/documentation/geocoding/intro#StatusCodes,您会看到以下可能的状态

  • “确定”
  • “零结果”
  • “ OVER_DAILY_LIMIT”
  • “ OVER_QUERY_LIMIT”
  • “ REQUEST_DENIED”
  • “ INVALID_REQUEST”
  • “ UNKNOWN_ERROR”

因此,在尝试访问$dataset->results[0]之前,请先检查$dataset->status的值。如果为“ OK”,则可以安全地获得结果,否则可以正确处理错误代码。

代码段可能是

 $dataset = json_decode($jsonResponse);

 if ($dataset->status == "OK") {
     if (isset($dataset->results[0])) {
         $latitude = $dataset->results[0]->geometry->location->lat;
         $longitude = $dataset->results[0]->geometry->location->lng;
     }
 } elseif ($dataset->status == "ZERO_RESULTS") {
     //TODO: process zero results response 
 } elseif ($dataset->status == "OVER_DAILY_LIMIT" {
     //TODO: process over daily quota 
 } elseif ($dataset->status == "OVER_QUERY_LIMIT" {
     //TODO: process over QPS quota  
 } elseif ($dataset->status == "REQUEST_DENIED" {
     //TODO: process request denied  
 } elseif ($dataset->status == "INVALID_REQUEST" {
     //TODO: process invalid request response  
 } elseif ($dataset->status == "UNKNOWN_ERROR" {
     //TODO: process unknown error response 
 }

我希望这会有所帮助!