PHP遍历Google Places API JSON获取照片引用遇阻求助
解决Google Places API提取photo_reference的问题
作为PHP新手踩这些API调用的坑太正常了,我帮你梳理下代码里的问题,一步步修正就能解决:
先揪出几个关键错误
- Places API URL变量解析失败
你用单引号包裹了请求URL,里面的$lat,$lng会被当作纯字符串输出,根本不会替换成实际的坐标值,导致请求的URL完全无效。 - 循环遍历的层级错了
你直接遍历整个$places_array,但Google Places API返回的所有地点数据都存在results字段里,得遍历$places_array['results']才能拿到每个地点的信息。 - 没处理无照片的情况
不是所有地点都有照片数据,直接提取会报错,得先检查photos字段是否存在再操作。
修正后的完整代码
<?php $photo_references = []; // 用来存储所有提取到的photo_reference if(!empty($_GET["location"])){ $API_key = "你的API密钥"; // 务必填上你在Google Cloud申请的有效密钥! // 1. 调用地理编码API获取坐标 $maps_url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($_GET['location']) . '&key=' . $API_key; $maps_json = file_get_contents($maps_url); $maps_array = json_decode($maps_json, true); // 检查地理编码请求是否成功 if($maps_array['status'] !== 'OK' || empty($maps_array['results'][0]['geometry']['location'])){ echo "无法获取该地点的坐标,请检查输入或API密钥"; exit; } $lat = $maps_array['results'][0]['geometry']['location']['lat']; $lng = $maps_array['results'][0]['geometry']['location']['lng']; // 2. 调用Places附近搜索API——注意:radius和rankby=distance不能同时用!二选一 $places_url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$lng&radius=1500&key=" . $API_key; // 如果想用距离排序,就改成:$places_url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$lng&rankby=distance&key=" . $API_key; $places_json = file_get_contents($places_url); $places_array = json_decode($places_json, true); // 检查Places API请求是否成功 if($places_array['status'] !== 'OK' || empty($places_array['results'])){ echo "无法获取附近地点,请检查API密钥或坐标"; exit; } // 3. 遍历地点列表,提取photo_reference foreach ($places_array['results'] as $place) { // 先判断当前地点是否有照片数据 if(isset($place['photos']) && !empty($place['photos'])){ // 遍历该地点的所有照片,提取reference foreach($place['photos'] as $photo){ if(isset($photo['photo_reference'])){ $photo_references[] = $photo['photo_reference']; } } } } // 测试输出提取结果 echo "<h3>提取到的Photo References:</h3>"; var_dump($photo_references); } ?> <!DOCTYPE html> <html lang="en"> <head> <title>What is Here?</title> </head> <body> <h1>Type in a location</h1> <p>This program will display pictures of places to go in that area</p> <form action ="" method="GET"> <input type ="text" name ="location" placeholder="输入地点"/> <button type ="submit">Go!</button> </form> <br/> <?php if(isset($lat) && isset($lng)) echo "$lat $lng"; ?> </body> </html>
额外注意事项
- API密钥必须配置:代码里的
$API_key是空的,一定要填上你在Google Cloud Console申请的密钥,同时确保Geocoding API、Places API、Place Photos API都已启用。 - 参数互斥问题:
radius和rankby=distance不能同时出现在请求里,否则Places API会返回错误,二选一即可。 - 兼容性备选:如果你的服务器禁用了
file_get_contents,可以换成cURL来发送请求,兼容性会更好。
内容的提问来源于stack exchange,提问作者Awz
相关产品推荐
相关产品推荐

