google distance matrix on localhost

南楼画角 提交于 2019-12-24 05:48:51

问题


I am trying to use google distance matrix to find out the distance and time from one source to one destination.

I am calling the function

$('#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);
    });
});

I just need to get whatever data is returned but the problem is whenever I load the page which has the link

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

or trigger the change in postcode field, it shows in the console the following 2 errors

  • Google Maps API error: MissingKeyMapError

  • No 'Access-Control-Allow-Origin' header is present on the requested
    resource. Origin 'http://localhost:60197' is therefore not allowed
    access.

There are two warnings as well

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

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

What am doing wrong, or whats the proper way of achieving the required output (distance and time between two points).


回答1:


Don't use the DistanceMatrix web service from javascript on the client, use the 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.
}

});



来源:https://stackoverflow.com/questions/40985434/google-distance-matrix-on-localhost

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