【发布时间】:2019-07-24 16:30:16
【问题描述】:
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