我是离子2的新用户,这是我的API用户列表,包含纬度和经度。我需要用谷歌地图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>
地理位置代码:
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);
});
答案 0 :(得分:0)
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
希望有所帮助