0

I'm building a website where the user, pressing a button, can see the first restaurant nearby his current location.

I made an ajax call using the places API of google, but I receive a CORS error. I looked for other answers but without success.

On Google's documentations I could not find an example to return only a JSON file instead a marker on the map.

I save on local storage some parameters that I use for the AJAX request, this is my code:

$('.button_find').click(function() {
      $.ajax({
        url: 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=restaurant&location=' + latitude + '%2C' + longitude + '&radius=' + (distance*1000) + '&key=' + key,
        type: 'GET',
        crossDomain: true,
        dataType: 'json',
        cache: false,
        success: function(response) {
          console.log(response);
        },
        error: function(e) {
          console.log('error: ' + e)
        }
      })
    })

If I open the request url on a new tab it works showing the json file with all the places, but return a CORS error when the request starts from my website:

Failed to load https://maps.googleapis.com/maps/api/place/textsearch/json?query=restaurant&location=51.0684368%2C13.7527327&radius=2000&key=...: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://dannyspina.ml' is therefore not allowed access.

Solutions?

Danny_DD
  • 756
  • 1
  • 12
  • 34
  • Try to user: dataType: 'jsonp', instead of dataType: 'json', – Nadeshwaran Aug 06 '18 at 10:37
  • 1
    The Places API endpoints are intentionally not CORS-enabled. See the answers at https://stackoverflow.com/questions/44336773/google-maps-api-no-access-control-allow-origin-header-is-present-on-the-reque/44339169#44339169 and https://stackoverflow.com/questions/43443836/cors-and-google-maps-http-api-calls/43444274#43444274 – sideshowbarker Aug 06 '18 at 10:37
  • @Nadeshwaran JSONP are no longer supported from Google API. – Danny_DD Aug 07 '18 at 14:12
  • @sideshowbarker thank you for the links, I'll check them out. – Danny_DD Aug 07 '18 at 14:12

0 Answers0