如何使用Google Places API展示场地照片?附代码示例
如何用Google Places API展示场地照片?
嘿,我来帮你补全这段代码,实现展示酒吧照片的功能~ 咱们一步步拆解来做:
首先得明确:Nearby Search接口只会返回场地的基础信息(比如名称、place_id),要拿到场地照片,得先通过Place Details API获取照片的photo_reference,再用Google Places Photo API的地址来加载图片。
完整实现代码
var str = ""; // 第一步:调用Nearby Search获取指定区域内的酒吧 $.ajax({ dataType: 'json', type: 'GET', url: 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.720032,-73.988354&radius=10000&type=bars&keyword=bar&key=YOUR_API_KEY', success: function(data) { // 遍历每个搜索结果 for(var dt in data.results) { var place = data.results[dt]; var placeName = place.name; var placeId = place.place_id; // 第二步:调用Place Details API获取场地详情(包含照片信息) $.ajax({ dataType: 'json', type: 'GET', url: `https://maps.googleapis.com/maps/api/place/details/json?placeid=${placeId}&key=YOUR_API_KEY`, success: function(detailsData) { var placeDetails = detailsData.result; var photoHtml = ''; // 检查当前场地是否有可用照片 if(placeDetails.photos && placeDetails.photos.length > 0) { // 取第一张照片,构造Photo API的访问URL var photoReference = placeDetails.photos[0].photo_reference; // 指定图片最大宽度为300px,也可以用maxheight参数 var photoUrl = `https://maps.googleapis.com/maps/api/place/photo?maxwidth=300&photoreference=${photoReference}&key=YOUR_API_KEY`; photoHtml = `<img src="${photoUrl}" alt="${placeDetails.name}" style="max-width:100%; height:auto;">`; } else { // 没有照片时显示占位文本 photoHtml = '<p>暂无场地照片</p>'; } // 将场地名称和照片添加到页面的ul列表中 $('ul').append(`<li><h3>${placeDetails.name}</h3>${photoHtml}</li>`); }, error: function(err) { console.error('获取场地详情失败:', err); $('ul').append(`<li>${placeName} - 加载详情失败</li>`); } }); } }, error: function(err) { console.error('获取附近场地失败:', err); $('ul').append('<li>加载附近酒吧失败,请检查API Key或网络状态</li>'); } });
关键细节说明
- 替换API Key:记得把代码里的
YOUR_API_KEY换成你自己的Google Cloud API Key,并且要确保已经在云控制台启用了「Places API」服务 - 照片参数说明:
- Place Details返回的
photos数组中,每个对象包含photo_reference(照片唯一标识)和该照片允许的最大尺寸(width/height) - Photo API的URL必须指定
maxwidth或maxheight(二选一即可),数值不能超过照片的最大尺寸限制
- Place Details返回的
- 异常处理:添加了error回调函数,方便调试API调用失败的情况
- 基础样式:给图片加了简单的样式,避免图片过大撑破页面布局
额外注意事项
- 确保你的API Key已经配置了正确的权限和计费方式(Google Places API有免费额度,超出后会产生费用)
- 嵌套AJAX请求可能会导致并发请求过多,如果需要处理大量搜索结果,建议用Promise或者批量请求的方式优化性能
内容的提问来源于stack exchange,提问作者tmar
相关产品推荐
相关产品推荐

