2016-12-05 100 views
2

我想用谷歌距離矩陣來找出從一個源到一個目的地的距離和時間。本地主機上的谷歌距離矩陣

我打電話的功能

$('#postCode').change(function() { 
    var address = "sydney"; 
    var source = "melbourne" 
    var url = "https://maps.googleapis.com/maps/api/distancematrix/js?units=imperial&origins=" + address + "&destinations=" + source + "&key=MYKEY_HERE"; 
    $.get(url, function (data) { 
     window.alert(data); 
    }); 
}); 

我只需要得到返回的任何數據,但問題是,每當我打開它具有鏈接

<script src="https://maps.google.com/maps/api/js?sensor=false?key=MYKEY_HERE"></script> 

的頁面或觸發的變化郵政編碼字段,它在控制檯中顯示以下2個錯誤

  • Google Maps API erro r:MissingKeyMapError

  • 否請求的
    資源上存在'Access-Control-Allow-Origin'標頭。原因'http://localhost:60197'因此不允許
    訪問。

有兩個警告以及

util.js中:210谷歌地圖API警告:NoApiKeys https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys

util.js中:210谷歌地圖API警告:SensorNotRequired https://developers.google.com/maps/documentation/javascript/error-messages#sensor-not-required

什麼我做錯了什麼,或者什麼是達到所需輸出的合適方式(兩點之間的距離和時間)。

回答

1

請勿在客戶端上使用javascript的DistanceMatrix web service,請使用Google Maps Javascript API v3 DistanceMatrix Service

$('#postCode').change(function() { 
    var address = "sydney"; 
    var source = "melbourne" 
var service = new google.maps.DistanceMatrixService(); 
service.getDistanceMatrix(
    { 
    origins: [address], 
    destinations: [source], 
    travelMode: 'DRIVING', 
    unitSystem: google.maps.UnitSystem.IMPERIAL, 
    }, callback); 

function callback(response, status) { 
    // See Parsing the Results for 
    // the basics of a callback function. 
} 

});

+0

我在哪裏放置API密鑰呢? – Novice

+0

如您所示,您已經在[Google Maps JavaScript API v3 include](https://developers.google.com/maps/documentation/javascript/get-api-key)中執行操作。 – geocodezip

+0

仍然有兩個錯誤和兩個警告 警告:沒有API密鑰 警告:不需要傳感器 錯誤:缺少鍵盤映射 錯誤:該服務需要一個API密鑰 – Novice