使用ionic2需要Google Directions Service的帮助。我试图通过路线功能计算它后设置距离和持续时间变量。当我在另一个方法(如onClickMap这里)访问时,该值将以未定义的形式出现。
以下是我创建的代码:
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
declare var google;
@IonicPage()
@Component({
selector: 'page-activity-detail',
templateUrl: 'activity-detail.html',
})
export class ActivityDetailPage {
public dist: any;
public dur: any;
latLng: any;
directionsDisplay = new google.maps.DirectionsRenderer;
constructor(public navCtrl: NavController, public navParams: NavParams, public geolocation: Geolocation) {
}
ionViewDidLoad() {
this.geolocation.getCurrentPosition().then((position) => {
this.latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
let destination = new google.maps.LatLng(this.activity.address.latitude, this.activity.address.longitude);
let directionService = new google.maps.DirectionsService;
directionService.route({
origin: this.latLng,
destination: destination,
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.IMPERIAL,
provideRouteAlternatives: false
}, function(response, status) {
if (status == 'OK') {
let t = 0;
let d = 0;
let myroute = response.routes[0];
console.log(myroute);
for (let i = 0; i < myroute.legs.length; i++) {
t += myroute.legs[i].distance.value;
d += myroute.legs[i].duration.value;
}
this.dist = t / 1000;
this.dur = d /60;
} else {
console.log(status);
}
});
}, (err) => {
console.log(err);
});
}
onClickMap(){
alert(this.dist);
alert(this.dur);
}
}