Batetambe Tanyi
Batetambe Tanyi

Reputation: 75

How to get an image from google places api?

I'm currently stuck on trying to get an image from the Google Places API, in the documentation is stated to get an image you have https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=[imagereference]&key=[yourkey]

This will then redirect you to a URL with the actual image. How do I do this process with axios or fetch as I'm trying to obtain the base 64 image version so that I can use inside my react application?

Upvotes: 1

Views: 1502

Answers (1)

Pagemag
Pagemag

Reputation: 2977

If you would like to show the Places API photo in client side applications, you need to use the Places Photos of the Google Maps JavaScript Places Library.

The code snippet below shows a sample of how I get the photo URL from the getDetails result and put it inside my state variables:

       const request = {
              placeId: "ChIJN1t_tDeuEmsRUsoyG83frY4",
              fields: [
                "name",
                "formatted_address",
                "place_id",
                "geometry",
                "photos"
              ]
            };

            const service = new google.maps.places.PlacesService(map);
            service.getDetails(request, (place, status) => {
              if (
                status === google.maps.places.PlacesServiceStatus.OK &&
                place &&
                place.geometry &&
                place.geometry.location
              ) {
                const marker = new google.maps.Marker({
                  map,
                  position: place.geometry.location
                });
              }
              this.setState({
                photos: place.photos[0].getUrl(),
                name: place.formatted_address
              });
            });

Here is the sample code and to see this work, replace the YOUR_API_KEY from the script inside Map.js with your API Key.

Upvotes: 1

Related Questions