Ionic 3谷歌距离矩阵API

问题描述 投票:1回答:1

我的基本想法是:我有一个分支列表,每个分支都有lat,lng属性,其中包含纬度和经度。我想使用Google Distance Matrix API来查找与每个分支的距离和持续时间。

这是我的代码。

Branches.ts (显示所有分支的页面,我也想在这里显示距离和持续时间)

//other imports
import { TravelDetailsProvider } from '../../providers/travel-details/travel-details';

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

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

  ionViewDidLoad() {
    this.getBranches();
  }

  getBranchDistanceAndTime(){
      for(let branch of this.allBranches){
        this.travelProvider.getTravelDetails(branch);
      }
  }

}

我知道我可能应该将返回的值分配给 branches.ts 中的一个变量,然后在视图中进行迭代,但是由于某些原因,我无法获得从 getTravelDetails() 办法

Travel-details.ts

declare var google;
var service = new google.maps.DistanceMatrixService();
@Injectable()
export class TravelDetailsProvider {

  private travelDetailsObject: any = {};

  constructor(public http: HttpClient) {
  }

  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.travelDetailsObject = travelDetailsObject;
   }
 }

}

当我运行这段代码时,我得到一个错误。Uncaught TypeError: Cannot set property 'travelDetailsObject' of null

在做了一些研究之后,我发现了这个github问题页面。我想知道这是不是我遇到的问题。https:/github.comrollbarrollbar.jsissues344。

谢谢你的帮助

google-maps typescript ionic3 google-distancematrix-api
1个回答
2
投票

你可以尝试

constructor() {
  this._mx = new google.maps.DistanceMatrixService();
}

getDistanceMatrix(req: DistanceMatrixRequest): Observable<DistanceMatrixResponse> {
  return Observable.create((observer) => {
    this._mx.getDistanceMatrix(req, (rsp, status) => {
      // status checking goes here
      observer.next(rsp);
      observer.complete();
    });
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.