这是我的代码:
declare var google;
var service = new google.maps.DistanceMatrixService();
class BranchesPage {
public branches: any = [];
public allBranches: any = [];
public travelDetails: any = [];
constructor(){
this.getBranches();
}
getBranches(){
this.travelDetails = [];
this.branchProvider.getBranches()
.subscribe(data => {
this.allBranches = data;
this.getBranchDistanceAndTime();
loadingBranches.dismiss();
}, err => {
console.log(err);
});
}
getBranchDistanceAndTime(){
for(let branch of this.allBranches){
this.getTravelDetails(branch);
}
}
getTravelDetails(branch){
service.getDistanceMatrix(
{
origins: [new google.maps.LatLng(6.870128,79.880340)],
destinations: [new google.maps.LatLng(branch.lat, branch.lng)],
travelMode: 'DRIVING'
}, this.callback);
}
callback(response, status) {
let travelDetailsObject;
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];
travelDetailsObject = {
distance: distance,
duration: duration
}
}
}
console.log(travelDetailsObject)//this works perfectly retrieving the correct distances and durations
this.travelDetails.push(travelDetailsObject); //error is on this line
}
}
我无法从回调函数访问travelDetails属性,因为它会引发以下异常Uncaught TypeError: Cannot read property 'travelDetails' of null
由于某种原因,this
关键字在回调函数中不可用。任何解决方法?我已经被困在这个问题上超过一天了。任何帮助将不胜感激。
谢谢你们
PS:在有人要求之前,branch.lat
和branch.lng
会按预期返回值。