2015-12-02 28 views
4

我試圖獲得direction_in_traffic,這是不使用常規方向api返回。我發現在distancematrix API中有一個字段可以做到這一點。Google DistanceMatrix API

,當我從我自己的機器運行此代碼的工作,但一旦它在網上,我看到關於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(); 
}; 

我創建了關鍵的錯誤,但在domain verification標籤似乎「忘記「我已經投入了什麼地址。

jsbin(這顯然不會工作,因爲這個密鑰不允許在該域名,但我在我自己的域名上得到相同的錯誤)。

完整的代碼,我在想這是可見的https://github.com/haroenv/maps-checker

感謝您的幫助!

+0

如果您的API密鑰鏈接到您的實際Google開發者帳戶,可能希望隱藏您的API密鑰。 – Vlad

+0

謝謝,沒有想到 –

+0

你可能想改變你的密鑰,許多網站吸SO帖子/修訂(點擊「editied ... ago」)。另外,你不應該從客戶端JS設置CORS頭文件,那些服務器響應頭文件。 – dandavis

回答

0

正如@dandavis在評論中所建議的,之所以這麼做沒有奏效,是因爲谷歌希望這個響應是服務器端的。我的解決方法如下:向Google反映請求的php(或任何服務器端解決方案)。一個示例實現是這樣的:

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

然後我從我的主客戶端腳本發送一個請求到該腳本。