如何在React Native中通过GET请求获取Google Maps Place图片?
解决Google Maps Place Photo API图片渲染问题
核心问题
你当前的错误在于把Place Photo API的响应当作JSON处理——这个API返回的是二进制图片数据,不是JSON格式,所以response.json()会报错,也根本不需要这一步。正确的做法是直接使用图片请求URL作为Image组件的数据源。
修正后的代码
const CardResturant = ({ resturant }) => { const [isLoading, setLoading] = useState(true); const [info, setInfo] = useState(null); const [imageUrl, setImageUrl] = useState(null); const [isImageLoading, setIsImageLoading] = useState(false); useEffect(() => { setLoading(true); fetch( `https://maps.googleapis.com/maps/api/place/details/json?place_id=${resturant.id}&key=KEY` ) .then((response) => response.json()) .then((json) => { setInfo(json); // 处理photos为空的边界情况 const photoRef = json?.result?.photos?.[0]?.photo_reference; if (photoRef) { // 直接生成图片URL,无需额外fetch const url = `https://maps.googleapis.com/maps/api/place/photo?maxwidth=100&photo_reference=${photoRef}&key=KEY`; setImageUrl(url); } }) .catch((error) => console.error(error)) .finally(() => setLoading(false)); }, [resturant.id]); // 添加依赖,确保resturant.id变化时重新请求 return ( <View> {isLoading ? ( <Text>LOADING</Text> ) : ( <View> <View> {isImageLoading && <Text>LOADING IMAGE</Text>} {imageUrl ? ( <Image source={{ uri: imageUrl }} style={{ width: 100, height: 100 }} // 必须设置宽高 onLoadStart={() => setIsImageLoading(true)} onLoadEnd={() => setIsImageLoading(false)} alt="Restaurant photo" /> ) : ( <Text>No photo available</Text> )} </View> </View> )} </View> ); };
关键修改点
- 移除冗余的图片fetch请求:Place Photo API的URL可以直接作为Image的
uri源,不需要额外fetch后解析JSON。 - 修正加载状态逻辑:初始
isLoading设为true,请求开始后保持true,完成后设为false,符合直观的加载状态展示。 - 添加边界处理:判断
photos是否存在,避免因无图片导致的报错,同时提供无图片时的提示。 - 完善Image组件配置:必须给Image设置宽高(React Native要求),添加加载状态监听,以及alt文本提升可访问性。
- 修复useEffect依赖:将
resturant.id加入依赖数组,确保当传入的resturant变化时,重新发起请求。
内容的提问来源于stack exchange,提问作者Tommaso Ceredi
相关产品推荐
相关产品推荐

