Google DistanceMatrix API

巧了我就是萌 提交于 2020-01-23 01:35:12

问题


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!


回答1:


So as @dandavis suggested in a comment, the reason why this didn't work is because Google wants this response to be server-side. My workaround is as follows: a php (or any server-side solution) that mirrors the request to Google. An example implementation is this:

<?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');
?>

And then I send a request to that script from within my main client-side script.



来源:https://stackoverflow.com/questions/34051871/google-distancematrix-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!