问题描述
我试图在 Google Maps API 中找到两点之间的距离矩阵,但我收到了这个错误。
Uncaught TypeError: Cannot read property 'apply' of undefined
at distance_matrix.js:4
at Ku.j (distance_matrix.js:3)
at Object.c [as _jr083s] (common.js:110)
at distanceMatrixService.GetdistanceMatrix?1m1&2s35.853308276088036&1m1&2s-
我正在尝试获取距离矩阵响应,以便获得以英里为单位的距离。这是我拥有的代码
function initMap() {
const momilets = { lat: 35.853308276088036,lng: -78.57256943168214};
const map = new google.maps.Map(document.getElementById('map'),{zoom: 12,center: momilets,disableDefaultUI: true});
const marker = new google.maps.Marker({position: momilets,map: map});
const geocoder = new google.maps.Geocoder();
document.getElementById('submit').addEventListener('click',() => {
geocodeAddress(geocoder,map);
})
}
function geocodeAddress(geocoder,resultsMap) {
const address = document.getElementById('address').value;
geocoder.geocode({ address: address },(results,status) => {
if(status = 'OK') {
resultsMap.setCenter(results[0].geometry.location);
const marker2 = new google.maps.Marker({
map: resultsMap,position: results[0].geometry.location,});
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
var service = new google.maps.distanceMatrixService();
service.getdistanceMatrix(
{
origins: ['35.853308276088036','-78.57256943168214'],destinations: [toString(lat),toString(lng)],unitSystem: google.maps.UnitSystem.IMPERIAL,travelMode: 'DRIVING'
} );
} else {
alert("Unsuccessful because: " + status);
}
});
}
function callback(response,status) {
if (status == 'OK') {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
var distance = element.distance.text;
var duration = element.duration.text;
var from = origins[i];
var to = destinations[j];
}
}
}
}
如果有人能帮我清除这个错误,我将不胜感激
解决方法
您没有在 service.getDistanceMatrix() 方法中提供回调函数,这就是为什么会出现上述错误。
service.getDistanceMatrix({
origins: ['35.853308276088036','-78.57256943168214'],destinations: [toString(lat),toString(lng)],unitSystem: google.maps.UnitSystem.IMPERIAL,travelMode: 'DRIVING'
},(response,status) => {
console.log("response data: ",response);
console.log("status: ",status);
});
您可以按照以下 JSFiddle 链接获取完整的工作代码。
<script async src="//jsfiddle.net/y4zbkudo/4/embed/js,html,css,result/dark/"></script>