Google 地理编码 API 不同的结果

Google Geocode API different results

我有一个有点奇怪的问题。 我正在做一个项目,需要知道我的 php 脚本中两个位置之间的距离。 您可以给 google api 城市名称或邮政编码。

嘿应该很简单吧?错了!

当然,我尝试使用已知的邮政编码和我所在的城市对其进行测试。 'Hannover' 和 '30159' 的距离应该在 0 左右,但奇怪的是我超过了 7200 公里。 (相信我,我计算 2 个坐标之间距离的代码有效)

现在进入实际问题。

我的步数:

  1. var_dump api 请求的结果
  2. 回显 url 用于 api 请求
  3. 在浏览器中打开 url 并比较输出

这是我的非常简单的代码。

$url = "https://maps.googleapis.com/maps/api/geocode/json?&address=".urlencode($ort)."&key=$google_api_key";
echo $url."<hr>";
$string = file_get_contents($url);
echo $string."<hr>";

现在这很奇怪。与 php 脚本相比,浏览器中的输出完全不同。

output compared browser vs script (sry I have no formatting for the script output)

有谁能向我解释 and/or 提供解决方案,使脚本的输出类似于德国境内邮政编码 30159 的浏览器的“所需”输出?

干杯耐萨留斯

好的,我想通了,如果有人遇到同样的问题,我想分享我的解决方案。

$url = "https://maps.googleapis.com/maps/api/geocode/json?&address=".urlencode($ort)."&key=$google_api_key";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, ["Accept-Language: de-DE-1996"]); // important
$string = curl_exec($curl);
curl_close($curl);

当您进行 ajax 调用时,浏览器会自动传输您的语言,但 php 函数不会。使用 curl,您可以指定您的语言,这使得 google api 报告与您所在地区最相关的值。