React Native - 如何显示Google Place Photos API返回的图片? [英] React Native - How can I display an image returned by Google Place Photos API?

查看:175
本文介绍了React Native - 如何显示Google Place Photos API返回的图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个后端API,它使用 Google Places Photos API

I have developed a backend API which given the latitude and longitude of a location it returns an image for the city using Google Places Photos API

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

My React Native app calls the endpoint to try and load the image into an Image view. This is how the app calls the endpoint and receives the response...

  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 app ...

The backend code for getting an image from Google and sending the response back to my React Native app...

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' }));
    })

您可以尝试使用端点查看成功时的响应情况这里

You may try the endpoint to see what the response looks like on success here

我不知道如何从响应中显示图像在图像视图中,因为响​​应不是带有网址或本地文件的网络图像。

I am not sure how to display the image from the response in an Image view since the response is not a network image with a url or a local file.

推荐答案

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

The Photos API returns an image like this: https://lh4.googleusercontent.com/-1wzlVdxiW14/USSFZnhNqxI/AAAAAAAABGw/YpdANqaoGh4/s1600-w400/Google%2BSydney

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

which you can use in an Image component as you would with any other network image:

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

我认为您的问题是您的回复不是实际图片,我的意思是,如果你在浏览器中点击它,您将看到没有图像只是一些编码的图像数据。尝试在此响应中添加一些内容类型标头,看看它是否有效:

I think the problem in your case is that your response is not an actual image, I mean if you hit it in a browser you'll see no image just some encoded image data. Try to add some content type headers in your response like this and see if it will work:

Content-Type: image/svg+xml 

这篇关于React Native - 如何显示Google Place Photos API返回的图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆