首页 > 解决方案 > React Native - 如何显示 Google Place Photos API 返回的图像?

问题描述

我开发了一个后端 API,它给出了一个位置的纬度和经度,它使用Google Places Photos API返回城市的图像

我的 React Native 应用程序调用端点来尝试将图像加载到Image视图中。这就是应用程序调用端点并接收响应的方式......

  try {
    let imageResponse = await fetch(
      `https://budgettrip.herokuapp.com/locationimage/${latitude}/${longitude}`
    );
    let response = await imageResponse;
    this.setState({ locationImage: response });
  } catch (error) {
    console.error('location image error', error);
  }

从 Google 获取图像并将响应发送回我的 React Native 应用程序的后端代码......

var locationimage = {
    uri: `https://maps.googleapis.com/maps/api/place/photo?photoreference=${photo_reference}&sensor=false&maxheight=1600&maxwidth=1600&key=${process.env.GOOGLE_PLACES_API_KEY}`,
    headers: {
      'User-Agent': 'Request-Promise'
    }
  };

  rp(locationimage)
    .then(function(repos) {
      res.send(repos);
    })
    .catch(function(err) {
      // API call failed...
      res.send(JSON.stringify({ error: 'Could not get image' }));
    })

您可以在此处尝试端点以查看成功时的响应

我不确定如何在Image视图中显示响应中的图像,因为响应不是带有 url 或本地文件的网络图像。

标签: javascriptreact-nativegoogle-places-apigoogle-places

解决方案


照片 API 返回如下图像: https ://lh4.googleusercontent.com/-1wzlVdxiW14/USSFZnhNqxI/AAAAAAAABGw/YpdANqaoGh4/s1600-w400/Google%2BSydney

您可以像使用任何其他网络图像一样在图像组件中使用它:

<Image
  style={styles.image}
  source={{
    uri:'https://lh4.googleusercontent.com/-1wzlVdxiW14/USSFZnhNqxI/AAAAAAAABGw/YpdANqaoGh4/s1600-w400/Google%2BSydney'
  }}
/>

我认为您的问题是您的响应不是实际图像,我的意思是如果您在浏览器中点击它,您将看不到任何图像,只是一些编码的图像数据。尝试像这样在您的响应中添加一些内容类型标题,看看它是否会起作用:

Content-Type: image/svg+xml 

推荐阅读