Cant access values returned by callback function in Google Distance Matrix API


#1
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, LoadingController } from 'ionic-angular';

import { BranchPage } from '../branch/branch';

import { BranchProvider } from '../../providers/branch/branch';

declare var google;
var service = new google.maps.DistanceMatrixService();

@IonicPage()
@Component({
  selector: 'page-branches',
  templateUrl: 'branches.html',
})
export class BranchesPage {

  public branches: any = [];
  public allBranches: any = [];

  public travelDetails;

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public branchProvider: BranchProvider,
    public travelProvider: TravelDetailsProvider,
    public loadingController: LoadingController
  ){
  }

  ionViewDidLoad() {
    this.getBranches();
    console.log('ionViewDidLoad BranchesPage');
  }

  getBranches(){
    this.travelDetails = [];
    let loadingBranches = this.loadingController.create({
      content: 'Loading branches'
    });
    loadingBranches.present();
    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
          }
        }
      }
      this.travelDetails.push(travelDetailsObject); //cannot execute this line
    }
  }

}

Basically, I want to get the travel distance and time for a particular branch and push it into my travelDetails object. But I get the following error:

Uncaught TypeError: Cannot read property 'travelDetails' of null
    at webpackJsonp.111.BranchesPage.callback

Any help would be great!