Google DistanceMatrix API

I am trying to get direction_in_trafficone that doesn't return using normal api directions. I found that distancematrixthere is a field in the api that does just that.

This code works when I run it from my own machine, but as soon as it is connected to the network, I see errors regarding 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 created a key, but on the tab domain verificationit seems to β€œforget”, which I add.

jsbin (which obviously will not work since this key is not allowed in this domain, but I get the same error on my own domain).

The full code I'm trying to do is shown at https://github.com/haroenv/maps-checker

Thank you for your help!

+4
1

@dandavis , , , , Google , . : php ( ), Google. :

<?php
echo file_get_contents('https://maps.googleapis.com/maps/api/distancematrix/json?origins=' . urlencode($_POST['from']) . '&destinations=' . urlencode($_POST['to']) . '&key='. urlencode(json_decode(file_get_contents('config.json'), true)['maps-key']) .'&mode=' . urlencode($_POST['mode']) . '&departure_time=now');
?>

script script.

0

Source: https://habr.com/ru/post/1618333/


All Articles