CORS and Google Maps Places Autocomplete API calls [duplicate]

The supported way to call the Place Autocomplete API from a web app is 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>

That way it doesn’t matter that the responses lack the Access-Control-Allow-Origin header.

Using the Maps JavaScript API that way—by way of a script element to load the library, and then using the google.maps.Map and other google.maps.* methods—is the only supported way. Google intentionally does not allow doing it by way of requests sent with XHR or the Fetch API.

Leave a Comment