用户的位置距离我目前的位置的距离
问题描述:
我是离子2的新手,这里是我的经纬度API用户列表。我需要使用Google地图API来显示我目前位置的用户距离?我如何在我的ts文件中使用下面的地理定位代码?用户的位置距离我目前的位置的距离
JSON:
data":[
{
"id":"1",
"name":"Adil",
"latitude":"21.560362",
"longitude":"39.134023"
},
{
"id":"2",
"name":"John",
"latitude":"22.560212",
"longitude":"39.133765"
},
{
"id":"3",
"name":"Muhammed",
"latitude":"22.560212",
"longitude":"39.133765"
}
]
TS文件:
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("PathToMyUsersApiFile").subscribe(data => {
this.items = JSON.parse(data['_body']).data;
}, error => {
console.log(error);
});
});
}
}
HTML:
<ion-list *ngFor="let item of items">
<ion-item>
<h2>{{item.name}}</h2>
<!-- distance from current location -->
<p>{{item.distance}}</p>
</ion-item>
</ion-list>
Geolo阳离子代码:
Geolocation.getCurrentPosition().then((position) => {
var currentLocation = {lat: position.coords.latitude, lng: position.coords.longitude};
var usersLocation = []; // Users location
var geocoder = new google.maps.Geocoder;
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [origin1],
destinations: usersLocation,
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== 'OK') {
alert('Error was: ' + status);
} else {
var results = response.rows[0].elements;
for (var j = 0; j < results.length; j++) {
console.log(results[j].distance.text + ' in ' + results[j].duration.text);
}
}
});
}, (err) => {
console.log(err);
});
答
constructor(private zone: NgZone) {
}
this.platform.ready().then(() => {
this.http.get("PathToMyUsersApiFile").subscribe(data => {
this.items = JSON.parse(data['_body']).data;
Geolocation.getCurrentPosition().then((position) => {
var currentLocation = {lat: position.coords.latitude, lng: position.coords.longitude};
var usersLocation = []; // Users location
var geocoder = new google.maps.Geocoder;
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [origin1],
destinations: usersLocation,
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, (response, status) => {
if (status !== 'OK') {
alert('Error was: ' + status);
} else {
var results = response.rows[0].elements;
this.zone.run(()=>{
for (var j = 0; j < results.length; j++) {
this.items[j].distance=results[j].distance.text
}
})
}
});
}, (err) => {
console.log(err);
});
}, error => {
console.log(error);
});
});
注意要点。
- 您还没有设定起源于代码
- 通知使用箭头功能,使
this
是可能的。(()=>{}
) - 有很多方法重构代码。像逻辑与移动到
service
并结合Observable
和Promise
flatMap
希望它帮助
请告诉我问题,你所面对? – raj
我不知道我需要放置地理位置代码以及如何获取列表中的{{item.distance}}值。 – shebi
如何将结果[j] .distance.text推送到this.items? – shebi