XMLHttpRequest cannot load http://maps.googleapis.com/maps/api/distancematrix/xml?origins=Affenhausen&destinations=Achenkirch&mode=driving&language=de-DE&sensor=false. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
The Javascript code is as
function distanceCalc(){
start_location = $('select.start option:selected').val();
target_location = $('select.end option:selected').val();
$.get('http://maps.googleapis.com/maps/api/distancematrix/xml?origins='+start_location+'&destinations='+target_location+'&mode=driving&language=de-DE&sensor=false', function(data) {
DreamWeaver works, but when I open it via a browser, I get the same error.
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...
}
}
Sounds like you have a crossdomain problem because there is no 'Access-Control-Allow-Origin' header in the response. If this is not the case a browser usually does not allow to request a service located on another domain than the javascript that is triggering the request.
Seems like the api you are using is not intended for this approach, maybe this can help: How to make cross-domain AJAX calls to Google Maps API?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With