Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get around the CORS issue in Google's API?

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?

like image 527
Rohan Avatar asked Jul 14 '15 11:07

Rohan


1 Answers

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.

like image 180
Shaun Whyte Avatar answered Oct 06 '22 00:10

Shaun Whyte