I'm trying to get the direction_in_traffic
, which isn't returned using the regular directions api. I've found that there is a field in the distancematrix
api that does just that.
This code works when I run it from my own machine, but once it is online, I see errors concerning Access-Control-Allow-Origin
var durationInTraffic = function(from, to, mode, callback) {
var key = 'API-KEY';
var address = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=' + from + '&destinations=' + to + '&key='+ key +'&travelmode=' + mode + '&departure_time=now';
var req = new XMLHttpRequest();
req.addEventListener('load', function(){
if (typeof callback === 'function') {
callback(JSON.parse(this.responseText).rows[0].elements[0].duration_in_traffic.value);
}
});
req.open('GET',address);
req.setRequestHeader('Access-Control-Allow-Origin','https://haroen.me');
req.setRequestHeader('Access-Control-Allow-Headers','X-Requested-With');
req.send();
};
I've created the key, but at the domain verification
tab it seems to "forget" what addres I've put in.
jsbin (which obviously won't work since this key isn't allowed on that domain, but I get the same error on my own domain).
The full code I'm trying this on is visible at https://github.com/haroenv/maps-checker
Thanks for your help!