问题
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