I'm trying to augment the collection of photos I have for public artworks in this project I'm working on with photos from the Google Places API. It says here that you can send a details request to get an array of ten photos. Eventually I will unpack the response to get Google's photo reference for each photo and make requests for each photo in the array and display it.
Unfortunately, this plan breaks when I send my details request. This is the exact error I'm getting:
Fetch API cannot load https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJ5zf5lfXKRIYR8rPafbwaL68&key=MY_API_KEY.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:4040' is therefore not allowed access.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I'm running this from my localhost and I'm pretty sure that matters. All of my other API calls (Google Maps API and a couple others) are written exactly as this is, so I'm a little confused why I'm getting the error. Here is the relevant code:
The actual API call:
export function getPhotos(placeID) {
let obj = {
method: 'GET'
};
return fetch('https://maps.googleapis.com/maps/api/place/details/json?placeid=' + placeID + '&key=MY_API_KEY')
.then((response) => {
if (response.status >= 400){
throw new Error("Error getting photos for placeID: " + placeID)
}
return response.json()
})
}
Let me know if you need any other information, I'd be happy to provide it. Thanks!
The previous answer suggests using a server-side proxy. While that is a good solution for the general case of accessing a web API that does not support CORS or JSONP, it's not the best solution for this specific problem.
Instead, use Google's JavaScript Places Library which is designed specifically for this kind of use. The links at the top of that page provide additional samples, guides, and reference material.