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?

3
  • "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. Commented Jul 14, 2015 at 11:13
  • 2
    Read the documentation which has a massive box at the top pointing towards a version of the API designed for client side JS. Commented Jul 14, 2015 at 11:19
  • Please refer to my answer regarding to the CORS issue there: How to bypass CORS issue ? Commented Jul 14, 2015 at 13:43

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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)
-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

Comments

-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>');  
   });  

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.