XMLHttpRequest cannot load, No ‘Access-Control-Allow-Origin’ header is present on the requested resource [duplicate]

This is a bit tricky, even if you have CORS set up properly it still fails. You should use Google’s build in functions to access it. If you try to access it directly via $.get() or similar it will fail… check this example out:
https://developers.google.com/maps/documentation/javascript/examples/distance-matrix

Interesting fact, when accessing via $.get() (I am not sure why though):

-THIS WORKS: http://maps.googleapis.com/maps/api/geocode/

-THIS FAILS: http://maps.googleapis.com/maps/api/distancematrix/

My advice – don’t try fetching json/xml via get(). Use google’s API build in functions to send request and then parse the response properly

This example code should get you started:

// var origins      = [];
// var destinations = [];

var distanceMatrix  = new google.maps.DistanceMatrixService();
var distanceRequest = { origins: origins, destinations: destinations, travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.METRIC, avoidHighways: false, avoidTolls: false };
distanceMatrix.getDistanceMatrix(distanceRequest, function(response, status) {
    if (status != google.maps.DistanceMatrixStatus.OK) {
        alert('Error was: ' + status);
    }
    else {
        var origins      = response.originAddresses;
        var destinations = response.destinationAddresses;
        // rest of your code here...
    }
}

Leave a Comment