Quesiton:
I have a small project that I am wanting to make that goes through a list of (around 300) names of places, and gets details about these places using the Google Maps Place Search API. If I take one of these places, and place the URL in my browser:
/* Replacing API_KEY with my API key
and PLACE_NAME with each place name */
"https://maps.googleapis.com/maps/api/place/textsearch/json?key=API_KEY&query=PLACE_NAME"
When I put that in my browser, it gives me the JSON result, just as we expect.
The problem I am having is in my <script>
tag in my HTML file. Where I do the following:
let result = await fetch('https://maps.googleapis.com/maps/api/place/textsearch/json?key=API_KEY&query=PLACE_NAME')
But I get the following CORS error:
Access to fetch at 'https://maps.googleapis.com/maps/api/place/textsearch/json?key=API_KEY&query=PLACE_NAME' from origin 'http://localhost:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I know very little about CORS and how to fix these kinds of errors. I've tried searching the web for solutions, but the things I found either didn't work for my project (e.g. importing a library using require()
) or was about a different Google Maps API. And obviously setting it to a no-cors
request is NOT what I want, as I will not be able to see the results.
Solution:
As this question was closed because it is a duplicate question, I wanted to edit my question to share the solution, because the answer to the question this is a duplicate of, points to the solution, but doesn't answer it.
The answer to that question talks about how the way I was trying was for a Web Service. There is the Places Library in the Google Maps JavaScript API, which is how you need to do this sort of thing client-side.
- Enable the Google Maps API on your Google Cloud dashboard.
- Import the Google Maps JavaScript Library:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=callBackFunction"></script>
- Then write your function (in another
<script>
tag) and create a newPlacesService
function getLocationData() {
// Because PlacesService requires a div or map element, we create this
const element = document.createElement('div');
// Create a new instance of PlaceService to use it's methods
const service = new google.maps.places.PlacesService(element);
// Use one of it's methods. In my case I need findPlaceFromQuery
service.findPlaceFromQuery(
// Choose what fields you want it to return (if the method requires)
{ fields: ['geometry'], query: data[i].name },
(results) => {
// Do your data processing here
})
}
And now it should work!