2

I am trying to get Angular talk to Google Maps Places Autocomplete API. The problem is that the server doesn't allow CORS calls (it doesn't return an Access-Control-Allow-Origin header) and JSONP calls also seem to be futile as it returns plain JSON and not JSONP, causing a syntax error.

This is what I am currently trying in a service function (_jsonp is a Jsonp object):

return this._jsonp.request(url, { method: 'GET' });

And this doesn't work. The response arrives, but Angular crashes because it's not JSONP but JSON.

This is crazy. How on earth can I access this if CORS is disabled and JSONP calls don't work?

https://maps.googleapis.com/maps/api/place/autocomplete/json?key=ACCESS_KEY&types=(cities)&input=ber

Is there a way to convert a JSON server response into a JSONP data object in the Observable pipeline?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Tamás Polgár
  • 2,082
  • 5
  • 21
  • 48

1 Answers1

1

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.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197