React Native - How can I display an image returned by Google Place Photos API?

六眼飞鱼酱① 提交于 2020-01-13 07:20:05

问题


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

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

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.


回答1:


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

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 


来源:https://stackoverflow.com/questions/50778775/react-native-how-can-i-display-an-image-returned-by-google-place-photos-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!