检查面向对象编程中是否存在密钥

问题描述 投票:-1回答:1

有时会丢失来自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;
php json google-maps object geocoding
1个回答
1
投票

您应该知道,Geocoding API Web服务还会在响应中返回状态。状态指示响应中是否存在有效项目或出现错误且您没有任何结果。

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

  • “好”
  • “ZERO_RESULTS”
  • “OVER_DAILY_LIMIT”
  • “OVER_QUERY_LIMIT”
  • “请求被拒绝”
  • “非法请求”
  • “未知错误”

因此,在您尝试访问$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 
 }

我希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.