dongtong7990 2016-10-25 13:39
浏览 44
已采纳

使用Google地图解码PHP中的API响应

I'm struggling to get the "Adams County" from "administrative_area_level_2" type from this api response http://maps.googleapis.com/maps/api/geocode/json?latlng=39.76144296429947,-104.8011589050293&sensor=false .

I simply need to output the county based on the latitude and longitude.

$query = @unserialize(file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng=39.76144296429947,-104.8011589050293&sensor=false'));
echo 'Hello visitor from '.$query["response"];

This is what I have for now. Thank you.

  • 写回答

2条回答 默认 最新

  • dtbsezxw28056 2016-10-25 13:54
    关注

    Use json_decode instead of unserialize, as the response is in JSON format.

    Then just iterate the items in a loop or two, for example:

    $url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=39.76144296429947,-104.8011589050293&sensor=false'; $response = json_decode(file_get_contents($url), true);
    if (empty($response['results'])) {
      // handle error
    }
    
    $long_name = null;
    
    foreach ($response['results'] as $r) {
      if (empty($r['address_components']) || empty($r['types']))
        continue;
    
    
      if (array_search('administrative_area_level_2', $r['types']) === false)
        continue;
    
      foreach ($r['address_components'] as $ac) {
        if (array_search('administrative_area_level_2', $ac['types']) !== false) {
          $long_name = $ac['long_name'];
          break;
        }
      }
    }
    
    echo $long_name;
    

    Output

    Adams County
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记