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