Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AJAX Basics (retiring) AJAX and APIs Stage 4 Challenge Answer

Alex Lumierre
Alex Lumierre
11,010 Points

https call using $.ajax()

Hi there, I'm trying to make an ajax call to google API. However, the API using httpS instead http. Therefore my code below throws an error:

  var googleAPI = 'https://maps.googleapis.com/maps/api/distancematrix/json?';
  var dataLocation = {
    origins:'56.333476,-2.781181',
    destinations:originPosition.coords.latitude+','+originPosition.coords.longitude,
    key:'AIzaSyCsSTtLd4ThP8xleny93jhTyx3jD8DUgKM'
  };

  $.getJSON(googleAPI,dataLocation, function(LocationRetrieved) {
    var distance = LocationRetrieved.rows.elements.distance.text;
    console.log(distance);

  });
}

Error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://maps.googleapis.com/maps/api/distancematrix/json?&origins=56.333476%2C-2.781181&destinations=56.333390699999995%2C-2.7830904&key=AIzaSyCsSTtLd4ThP8xleny93jhTyx3jD8DUgKM. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

Any suggestion of how to fix this?

3 Answers

Erwin Meesters
Erwin Meesters
15,088 Points

Have you tried leaving off the https?

Try: var googleAPI = '//maps.googleapis.com/maps/api/distancematrix/json?';

Alex Lumierre
Alex Lumierre
11,010 Points

This will re-direct me to https...

Alex Lumierre
Alex Lumierre
11,010 Points

Hi. I found out that this happens because I try to run ajax in my local machine. Now as far as I understand, ajax runs in web server. Any comment regarding this?

Erwin Meesters
Erwin Meesters
15,088 Points

Take a look at this: http://stackoverflow.com/questions/2921745/how-to-make-cross-domain-ajax-calls-to-google-maps-api

Google Maps provides a full featured Client-side Geocoding API for JavaScript.

Alex Lumierre
Alex Lumierre
11,010 Points

Hi Erwin! thank you so much for the link