Search code examples
javascriptgoogle-maps-api-3google-places-api

JavaScript: How to store photo data obtained from Google's Place Photo API


I am developing a backend in Node.js that uses the Google Places API. I wish to get a photo from the API based on a search string on the destination, and then pass the photo to the front-end

My code looks like the following

searchStr = 'Hilton hotel in Toronto';

// get photo reference from Google Places API
config = {
    method: 'get',
    url: `https://maps.googleapis.com/maps/api/place/textsearch/json?
          query=${searchStr}&key=${MY_API_KEY}`
    headers: {}
}
photo_ref = await axios(config).then(res => res.data.results[0]['photos'][0]['photo_reference']);

// get photo from Google Places based on photo reference
photoConfig = {
    method:'get',
    url: `https://maps.googleapis.com/maps/api/place/photo?
          photo_reference=${photo_ref}&key=${MY_API_KEY}`
    headers: {}
}
// WHAT SHOULD I DO HERE?

Through debugging, it seemed that I was able to get the proper photo reference, and create photoConfig with the correct url. But what should I do next? How can I store the image format with axios(photoConfig) and pass it to the frontend.

FYI, I am using Express, so passing to the frontend would look like

res.send(some JSON)

Solution

  • A backend cannot "pass to the frontend" anything on its own initiative, it can only send an HTTP response after the frontend made an HTTP request. Such an HTTP request is, for example, triggered by an <img> element on an HTML page, and the HTTP response would consist of the image itself. An HTTP request for a JSON response can be made through the Javascript fetch method. You must decide which variant you need.

    The following express middleware uses the code from your question and responds to an HTTP request made by an <img> element. It simply forwards the response obtained from maps.googleapis.com:

    app.get("/image", function(req, res) {
      ... your code ...
      https.get(`https://maps.googleapis.com/maps/api/place/photo?photo_reference=${photo_ref}&key=${MY_API_KEY}`)
      .on("response", function(r) {
        res.writeHead(r.statusCode, r.statusMessage, r.headers);
        r.pipe(res);
      });
    });
    

    Note this leaves open the question how you can vary the search string in your application.