You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何加速Google Place及图片获取?能否单次请求获取图片URL?

解决方案

首先明确:Google Places Text Search API不会在首次请求时直接返回图片的可访问URL,只会返回photo_reference、尺寸等元数据,但你可以通过两种方式大幅优化当前的响应速度:


1. 直接返回图片API链接给前端,跳过后端二次请求

你当前代码里后端主动请求图片并转base64是最大的性能瓶颈。其实可以直接把拼接好的图片API URL返回给前端,让前端浏览器自行加载图片。这样后端不需要处理二进制数据,也省去了循环串行请求的耗时。

修改后的核心代码片段:

if ((business.photos ?? []).length > 0) {
    let { width = 1200, height = 1200, photo_reference } = business.photos[0];
    // 直接生成图片URL返回给前端,无需后端请求转base64
    businessDetails.photo = `https://maps.googleapis.com/maps/api/place/photo?photoreference=${photo_reference}&sensor=false&maxheight=${height}&maxwidth=${width}&key=${apiKey}`;
} else {
    businessDetails.photo = business.icon;
}

2. 并行请求图片(若必须后端处理)

如果业务上必须在后端处理图片(比如转base64存储),不要用串行循环请求,改用Promise.all并行发起所有图片请求,总耗时会从所有请求时间的总和降到单个请求的最长耗时。

修改后的核心代码片段:

if ((results ?? []).length > 0) {
    // 先整理所有需要请求图片的任务
    const businessPromises = results.map(async (business) => {
        let businessDetails = {
            // 填充其他字段
        };
        if ((business.photos ?? []).length > 0) {
            let { width = 1200, height = 1200, photo_reference } = business.photos[0];
            let photoUrl = `https://maps.googleapis.com/maps/api/place/photo?photoreference=${photo_reference}&sensor=false&maxheight=${height}&maxwidth=${width}&key=${apiKey}`;
            try {
                let businessPhotoResponse = await axios.get(photoUrl, { responseType: 'arraybuffer' });
                let imageBuffer = businessPhotoResponse.data;
                let base64Image = Buffer.from(imageBuffer, 'binary').toString('base64');
                businessDetails.photo = `data:${businessPhotoResponse.headers['content-type']};base64,${base64Image}`;
            } catch (e) {
                businessDetails.photo = business.icon;
            }
        } else {
            businessDetails.photo = business.icon;
        }
        return businessDetails;
    });
    // 并行执行所有请求
    businessResults = await Promise.all(businessPromises);
}

内容的提问来源于stack exchange,提问作者ololo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 05:48:24