19

I've seen this question asked by multiple people, none of the answers have worked for me.

I'm trying to make an API call to the google maps api with react/axios.

This is my get request:

componentDidMount() {
  axios({
   method : 'get',
   url : `http://maps.googleapis.com/maps/api/js?key=${key}/`,
   headers: {
     "Access-Control-Allow-Origin": '*'
     "Access-Control-Allow-Methods": 'GET',
   },
  })
 .then(function (response) {
  console.log(response);
 })
 .catch(function (error) {
  console.log(error);
 });
}

This is the error msg:

XMLHttpRequest cannot load http://maps.googleapis.com/maps/api/js?
key=xxxxxxxxx/. Response to preflight request doesn't pass access control 
check: No 'Access-Control-Allow-Origin' header is present on the 
requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

I've read the article con CORS that everyone else points to https://www.html5rocks.com/en/tutorials/cors/

but I can't find an answer to my problem there.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
jaimefps
  • 2,244
  • 8
  • 22
  • 45

1 Answers1

23

https://maps.googleapis.com/maps/api doesn’t support getting requests from frontend JavaScript running in web apps in the way your code is trying to use it.

Instead you must use the supported Google Maps JavaScript API, the client-side code for which is different from what you’re trying. A sample for the Distance Matrix service looks more like:

<script>
  var service = new google.maps.DistanceMatrixService;
  service.getDistanceMatrix({
    origins: [origin1, origin2],
    destinations: [destinationA, destinationB],
    travelMode: 'DRIVING',
    unitSystem: google.maps.UnitSystem.METRIC,
    avoidHighways: false,
    avoidTolls: false
},…
</script>

<script async defer
  src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>

And here’s an example for using the Place Autocomplete API using the Places library:

<script>
  function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: -33.8688, lng: 151.2195},
      zoom: 13
    });
    ...
    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);
    var autocomplete = new google.maps.places.Autocomplete(input);
    autocomplete.bindTo('bounds', map);
    var infowindow = new google.maps.InfoWindow();
    var infowindowContent = document.getElementById('infowindow-content');
    infowindow.setContent(infowindowContent);
    var marker = new google.maps.Marker({
      map: map,
      anchorPoint: new google.maps.Point(0, -29)
    });
</script>
<script
  src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap"
  async defer></script>

Using the Maps JavaScript API like that—by way of a script element to load the library, then using the google.maps.Map and other google.maps.* methods—is the only supported way to make requests to the Google Maps API from frontend JavaScript code running a browser.

Google intentionally doesn’t allow access to the Google Maps API by way of requests sent with axios or AJAX methods in other such libraries, nor directly with XHR or the Fetch API.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
  • 1
    Any idea how the sdk can call the api endpoints and not get CORS error? I have tried looking at the endpoint it calls, and tried to call it directly from my javascript, but it gives me CORS error. Just trying to understand how the sdk bypasses CORS – gaurav5430 Dec 27 '19 at 18:30
  • @gaurav5430 the SDK is loaded from Google's domain and therefore has access to it – Phil Mar 26 '21 at 04:47
  • 2
    @Phil that's not true, the script once loaded, executes in the current domain context, and any calls to the google api endpoints would be from the current domain and not the domain where the script was hosted. In this case, it seems they use jsonp to get around CORS – gaurav5430 Apr 08 '21 at 08:15
  • 1
    @sideshowbarker I'm stuck with same issue and reached here. I understand your point but then why I'm allowed to fetch data using Postman tool but not via axios call in my app ? Ex: I tried https://maps.googleapis.com/maps/api/place/textsearch/json?query=restaurants+toronto+canada&key= and it is working fine. – sandy Jul 06 '21 at 10:01
  • 1
    This does not seem to be a complete answer anymore. When using the Maps JavaScript API it eventually makes a request to https://maps.googleapis.com/maps/api/place/js/AutocompletionService.GetPredictionsJson and that request has no CORS headers in the response, so with a strict COEP the autocomplete fails despite using the JS API – Andreas Apr 01 '22 at 22:05