【问题标题】:Google Map Geocode API returns null谷歌地图地理编码 API 返回 null
【发布时间】:2016-03-23 21:37:12
【问题描述】:

当我尝试通过 URL 调用 Google Maps Geocode API 时,它可以正常工作并返回正确的 JSON。

例如,这是 URL:

https://maps.googleapis.com/maps/api/geocode/json?address=2140+Amphitheatre+Parkway,+Mountain+View,+IN&key=AIzaSyCUDSJ2GBE1DHupbAZT4u8gZqclkIhmb0M

当我尝试对我的 PHP 代码进行相同操作时,它返回 null。

下面是我的代码:

<?php
 
function lookup($string){
 
   $string = str_replace (" ", "+", urlencode($string));
   $details_url = "http://maps.googleapis.com/maps/api/geocode/json?address=".$string."&sensor=false";
 
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $details_url);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   $response = json_decode(curl_exec($ch), true);
 
   // If Status Code is ZERO_RESULTS, OVER_QUERY_LIMIT, REQUEST_DENIED or INVALID_REQUEST
   if ($response['status'] != 'OK') {
    return null;
   }
 
   print_r($response);
   $geometry = $response['results'][0]['geometry'];
 
    $longitude = $geometry['location']['lat'];
    $latitude = $geometry['location']['lng'];
 
    $array = array(
        'latitude' => $geometry['location']['lng'],
        'longitude' => $geometry['location']['lat'],
        'location_type' => $geometry['location_type'],
    );
 
    return $array;
 
}
 
$city = 'San Francisco, USA';
 
$array = lookup($city);
var_dump($array);
 
?>
</pre>

我尝试添加和删除 API 密钥,但它仍然返回 null。

感谢任何支持。

【问题讨论】:

  • 你是否包含了你需要的所有东西? + 打开错误报告?也许您遇到了错误或其他问题?
  • 它工作正常我已经在我的本地主机上检查过它并且工作正常。我得到这个数组(3) { ["latitude"]=> float(-122.4194155) ["longitude"]=> float(37.7749295) ["location_type"]=> string(11) "APPROXIMATE"
  • 我很困惑,为什么它没有返回任何东西
  • @Vivek 你能发布你的代码吗
  • 这不是您问题的真正答案,但是通过javascript获取数据,然后将数据上传到服务器怎么样?

标签: php google-maps google-maps-api-3 geocoding google-geocoder


【解决方案1】:

看起来代码很好并且运行良好,您只需要检查是否启用了 curl。我认为这就是您无法使用 php 获取数据的原因。

【讨论】:

    猜你喜欢
    • 2012-04-10
    • 2015-06-27
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多