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个错误

  • 谷歌地图 API 错误:MissingKeyMapError


  • 请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许 访问源“ http://localhost:60197 ”。

还有两个警告

util.js:210 Google Maps API 警告:NoApiKeys https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys

util.js:210 Google Maps API 警告:SensorNotRequired https://developers.google.com/maps/documentation/javascript/error-messages#sensor-not-required

做错了什么,或者实现所需输出的正确方法是什么(两点之间的距离和时间)。

4

1 回答 1

1

不要在客户端使用来自 javascript的DistanceMatrix 网络服务,请使用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.
}

});

于 2016-12-05T23:55:33.727 回答