Google地理编码格式问题。接收到未定义的偏移错误

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

我得到这个PHP通知:第9行的未定义偏移量:0。这与下面提供的代码中的Google Geocode API有关。

当您尝试引用位​​置0处的数组值但该位置不存在时,发生未定义的偏移量错误。我假设Google地理编码API在去年内发生了变化。由于它必须返回与最初编程的结果结构不同的结果结构。但是,尽管我知道这一点,但是我找不到任何错误的代码。有人知道我的代码格式不正确吗?

下面的代码从输入表单中提取国家和城镇字段。 Google Geocode计算出城镇的经度和纬度,然后将其馈送到时区API以计算时区。为了安全起见,我已经隐藏了我的API密钥。任何帮助表示赞赏。谢谢。

<?php
$town = urldecode($_GET['town']);
$country = urldecode($_GET['country']);

if(!empty($_GET['state'])){
  $state = urldecode($_GET['state']);
}

$location = json_decode(@file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?key=API_KEY_HERE&address='.urlencode($town.', '.(!empty($state) ? $state.', ' : '').$country)), true)['results'][0]['geometry']['location'];



$timezone = json_decode(@file_get_contents('https://maps.googleapis.com/maps/api/timezone/json?key=API_KEY_HERE&location='.$location['lat'].','.$location['lng'].'&timestamp='.date('U')), true);



$time = $timezone['rawOffset'] / 60 / 60;



echo $time;
?>
google-api timezone google-geocoding-api geocode google-geolocation
1个回答
0
投票

您的代码的这一部分就是问题所在:

)['results'][0]['geometry']['location']

您假设始终在位置0(第一项)处有结果。如果发生错误,结果数组将为空,因此位置0上没有结果。

API结果结构未更改。 Google不会这样做,因为它会破坏很多应用程序。更有可能是一组特定的输入(例如无效地址)给出了错误响应。

看看the documentation here。注意"status"字段,其中包含各种status codes。如果状态为"OK",则应将代码修改为only尝试从结果中获取项目。

在事物的时区方面,您也应该检查那里的状态代码。 (Here are the docs.)然后,在大多数情况下,应采用timeZoneId而不是rawOffset。您可以将该ID与PHP的内置时区功能(DateTime, DateTimeZone classes, etc.)结合使用。

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