使用Google Places API通过照片引用获取照片返回空JSON的问题
问题描述
我正在实现一个使用Google Places API的后端,希望通过照片引用获取地点照片。现有代码先通过文本搜索API获取photo_reference,再调用照片API,但使用axios请求后返回的photo_result是空JSON,我期望它是包含照片或照片URL的JSON格式,请问哪里出错了?
代码如下:
const str = 'hotels in toronto'; // get photo reference let config = { method: 'get', url: `https://maps.googleapis.com/maps/api/place/textsearch/json? query=${str}&key=${GOOGLE API KEY}`, headers: {} } let result = await axios(config); let photo_ref = result.data.results[0]['photos'][0]['photo_reference'] // using photo reference to get photo let photo_config = { method: 'get', url: `https://maps.googleapis.com/maps/api/place/photo? photo_reference=${photo_ref}&key=${GOOGLE API KEY}`, headers: {} } let photo_result = await axios(photo_config); console.log(JSON.stringify(photo_result))
问题原因与解决办法
核心问题:Place Photo API不返回JSON
Google Places Photo API的设计是直接返回图片二进制数据(比如JPEG格式),而非JSON结构。你的代码用axios默认的JSON解析方式处理响应,自然会得到空JSON对象。必须补充的必填参数
你的照片API请求缺少maxwidth或maxheight参数(二选一即可,取值范围1-1600),这是API的强制要求,不传会直接返回错误。两种可行解决思路
后端获取图片二进制并转成可使用格式
修改axios配置,设置responseType为arraybuffer,拿到图片二进制内容后转成base64格式,即可返回给前端直接使用:let photo_config = { method: 'get', url: `https://maps.googleapis.com/maps/api/place/photo? photo_reference=${photo_ref}&maxwidth=1000&key=${GOOGLE API KEY}`, responseType: 'arraybuffer' // 关键配置 } let photo_result = await axios(photo_config); // 转成base64格式的图片链接 const base64Image = Buffer.from(photo_result.data, 'binary').toString('base64'); const imageUrl = `data:image/jpeg;base64,${base64Image}`; console.log(imageUrl);直接返回照片API的URL给前端
不需要后端请求图片,直接把拼接好的照片API URL返回给前端,前端可以直接将这个URL作为<img>标签的src属性值:const photoUrl = `https://maps.googleapis.com/maps/api/place/photo?photo_reference=${photo_ref}&maxwidth=1000&key=${GOOGLE API KEY}`; // 将photoUrl返回给前端即可
内容的提问来源于stack exchange,提问作者J Qin
相关产品推荐
相关产品推荐

