1

I am trying to get JSON (gas stations in some radius) from google-map-api with the following code:

    var xhr = new XMLHttpRequest();

    xhr.open('GET', 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=50.4016469,30.6269542&radius=500&keyword=%D0%B7%D0%B0%D0%BF%D1%80%D0%B0%D0%B2%D0%BA%D0%B0&key=AIzaSyDdzZrGvAKqSRj7NHxsW6FqGpx8Bi_nCFw', false);
    xhr.onload = function() {
      alert(this.responseText);
    }
    xhr.onerror = function() {
      alert('Error ' + this.status);
    }
    xhr.send();

And have an eroor with CORS «Access-Control-Allow-Origin». Is there any way to get data from google map api?

Angry B
  • 305
  • 2
  • 17
  • 2
    You can prefix the request URL with `https://cors-anywhere.herokuapp.com/`: `xhr.open('GET', 'https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=50.4016469,30.6269542&radius=500&keyword=%D0%B7%D0%B0%D0%BF%D1%80%D0%B0%D0%B2%D0%BA%D0%B0&key=AIzaSyDdzZrGvAKqSRj7NHxsW6FqGpx8Bi_nCFw', true)`. See the *How to fix “Access-Control-Allow-Origin header must not be the wildcard” problems* part of the answer at https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe/43881141#43881141 – sideshowbarker Sep 18 '17 at 20:41
  • Yeah it works but you need to realize that when you use that, you’re also sending your API key to that third-party proxy. Anyway you also need to understand that the supported way to work with the Google Maps API from frontend JavaScript code running in browser is use the Google Maps JavaScript API documented at https://developers.google.com/maps/documentation/javascript/tutorial, the client-side code for which is very different from what you’re trying. For a lot of reasons, you probably want to be using that instead. – sideshowbarker Sep 18 '17 at 20:50
  • 1
    And incidentally you really never want to be giving `false` for the *async* argument of `XMLHttpRequest.open(…)`. – sideshowbarker Sep 18 '17 at 20:52

0 Answers0