0

I have a function in which I am using AJAX to make a call to the Google Places API, but this is returning a CORS error. The API is both a client and server API, thus the API does allow CORS, but I'm still getting an error. JSONP is not supported.

I have a AJAX call exactly like this elsewhere in my code that makes a call to the Geocode endpoint and it's been working fine. I only get the CORS errors when trying to use the Places endpoint.

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[MY_KEY]&libraries=places" async defer>
function getPlaceDetails(placeid) {
  $.ajax({
    url: 'https://maps.googleapis.com/maps/api/place/details/json?placeid='+placeid+'&key=[MY_KEY]'
  }).done(function(res) {
    console.log(res);                
  }).fail(function(err) {    
    console.log('Error: ' + err.status);
    console.log(err);
  });   
}

enter image description here

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
kennsorr
  • 292
  • 3
  • 20
  • 3
    If you want to access the Places API from javascript, use the Google Maps Javascript API v3 Places Library, not the Web Service. – geocodezip Feb 06 '18 at 16:20
  • Possible duplicate of [Sending a details request to Google Places API - (CORS error)](https://stackoverflow.com/questions/38542306/sending-a-details-request-to-google-places-api-cors-error) – geocodezip Feb 06 '18 at 16:27

1 Answers1

0

As @geocodezip mentioned, rather than making another AJAX call, use the places library already included. Just make sure it's included in the query string like:

src="https://maps.googleapis.com/maps/api/js?key=[MY_KEY]&libraries=places" async defer

Then you'll have .getDetails() available for use.

    var request = {
          placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4'
        };
    service = new google.maps.places.PlacesService(map);
    service.getDetails(request, callback);

    function callback(place, status) {
      if (status == google.maps.places.PlacesServiceStatus.OK) {
        createMarker(place);
      }
    }
kennsorr
  • 292
  • 3
  • 20