10

I am working on an application where I have to fetch elevation for some points using Google's elevation API and I am stuck on the infamous CORS problem.

var elevationUrl = 'https://maps.googleapis.com/maps/api/elevation/json?locations=39.7391536,-104.9847034&key=AIzaSyAgXFgUVR4Nia7pegX_0hcz0aNevCKAa58';

$.ajax({
    url: elevationUrl,
    type: 'GET',
    // dataType: 'JSONP',
    success: function(){
    }
});

For starters I just tried to query a fixed point. When I do this, I get a CORS alert in my browser's console.

When I tried the dataType: 'JSONP', it works and I get a response from the API but my browser complains that the response has an error in the response which it doesn't. Basically I am trying to parse JSON as JSONP which is why I am getting the syntax error in the response.

What is the way around this? How to query the Elevation API via AJAX calls?

Rohan
  • 13,308
  • 21
  • 81
  • 154
  • "my browser complains that the response has an error in the response" — What, precisely, does it complain about? Quote the error message, don't just describe it in vague terms. – Quentin Jul 14 '15 at 11:13
  • 2
    [Read the documentation](https://developers.google.com/maps/documentation/elevation/) which has a massive box at the top pointing towards a version of the API designed for client side JS. – Quentin Jul 14 '15 at 11:19
  • Please refer to my answer regarding to the CORS issue there: [How to bypass CORS issue ?](http://stackoverflow.com/questions/20433655/no-access-control-allow-origin-header-is-present-on-the-requested-resource-or/30014915#30014915) – Nizar B. Jul 14 '15 at 13:43

3 Answers3

3

If you have a backend api for your site you can make simple endpoint to pass through to the google api and execute the google result on the server, where the CORS header doesnt matter. Gives you the benefit of having a better caching system as well.

  • I am not sure what I was doing 6 years back, but yeah, a proxy API in my own back end seems like a good way to go about this problem to avoid CORS problem! B) – Rohan May 07 '21 at 11:55
-1

I use the Allow-Control-Allow-Origin plugin for chrome to get around this kind of thing. It will allow you to enable/disable CORS in chrome. https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

CiaranC
  • 34
  • 4
-2
https://medium.com/@akhouri/cors-issues-and-resolutions-803e6abda52a

OR

Make data type to jsonp

$('#btnAll').click(function () {  
$.ajax({  
   type: 'Get',  
   url: 'http://localhost:60545/api/student',  
   dataType: 'jsonp',  
success: function myfunction(data) {  
   $.each(data, function myfunction(index, val) {  
      $('#ulStudents').append('<li>' + val.FirstName + '' + val.LastName + '</li>');  
   });  

}

ashish bandiwar
  • 378
  • 1
  • 3
  • 12