我正在使用ionic2 app。我要做的是使用Google Maps API DistanceMatrixService和http.get计算API中当前位置和用户位置之间的距离。
此处我使用的是API http://abithacoirmat.com/md/api/v1/nearby,其中包含具有纬度和经度的用户列表。我需要列出距离我当前位置的用户。
export class AboutPage {
public items: any;
constructor(public navCtrl: NavController, public navParams: NavParams, public http: Http, public platform: Platform) {
this.http = http;
this.platform = platform;
this.platform.ready().then(() => {
this.http.get("http://abithacoirmat.com/md/api/v1/nearby").subscribe(data => {
this.items = JSON.parse(data['_body']).data;
//Destination array for google map destinations
var destArr = [];
for (let i = 0; i < this.items.length; i++) {
destArr.push({
lat: Number(this.items[i].latitude),
lng: Number(this.items[i].longitude)
});
}
Geolocation.getCurrentPosition().then((position) => {
var origin1 = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var geocoder = new google.maps.Geocoder;
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [origin1],
destinations: destArr,
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== 'OK') {
alert('Error was: ' + status);
} else {
var originList = response.originAddresses;
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
console.log(results[j].distance.text + ' in ' + results[j].duration.text);
//this.items[j].distance = results[j].distance.text + ' in ' + results[j].duration.text;
}
}
}
});
}, (err) => {
console.log(err);
});
}, error => {
console.log(error);
});
});
}
}
HTML
<ion-header>
<ion-navbar>
<ion-title>Nearby</ion-title>
</ion-navbar>
</ion-header>
<ion-content class="mapbg">
<ion-list>
<ion-item-sliding *ngFor="let item of items">
<ion-item>
<ion-thumbnail item-left>
<img class="thmb" src="{{item.image}}">
</ion-thumbnail>
<h2>{{item.name}}</h2>
<p>{{item.model}}</p>
<p>{{item.distance}}</p>
</ion-item>
</ion-item-sliding>
</ion-list>
</ion-content>
当我尝试使用此代码时:this.items[j].distance = results[j].distance.text + ' in ' + results[j].duration.text;
我收到运行时错误 无法读取未定义的属性“0”
答案 0 :(得分:0)
更改
}, function(response, status) {
if (status !== 'OK') {
到
}, (response, status)=>{
if (status !== 'OK') {
如果您使用功能而不是胖箭头符号,那么您将无法引用该页面。
我建议您阅读:https://stackoverflow.com/a/20279485/5706293
回答第二个问题:为了显示异步数据,请更改您的html表示法:
{{item?.name}} {{item?.distance}}
安全导航操作符(?)检查数据是否为空,然后执行其余操作。