我是新来的Ionic2,我按照这个教程,它完美地工作https://www.joshmorony.com/create-a-nearby-places-list-with-google-maps-in-ionic-2-part-1/,它列出了一些地方,然后计算距离在这些地方和硬编码的地方之间,我想要实现的是使用当前位置而不是代码中给出的位置,以下是我迄今取得的屏幕截图screenshot of my application 以下是我的位置提供程序:当我使用“position.coords.latitude”试图获得当前位置时,我得到了一个undefined
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import {Geolocation} from '@ionic-native/geolocation';
/*
Generated class for the LocationsProvider provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class LocationsProvider {
data: any;
Currentlatitude: any;
Currentlongitude: any;
constructor(public http: Http, public geolocation: Geolocation) {
console.log('Hello LocationsProvider Provider');
}
load(){
this.geolocation.watchPosition().subscribe((position) => {
this.Currentlatitude = position.coords.latitude;
this.Currentlongitude = position.coords.longitude;
});
if(this.data){
return Promise.resolve(this.data);
}
return new Promise(resolve => {
this.http.get('assets/data/locations.json').map(res => res.json()).subscribe(data => {
this.data = this.applyHaversine(data.locations);
this.data.sort((locationA, locationB) => {
return locationA.distance - locationB.distance;
});
resolve(this.data);
});
});
}
applyHaversine(locations){
// this must change according to the device location
/*
let usersLocation = {
lat: 40.713744,
lng: -74.009056
}; */
console.log("this.Currentlatitude ",this.Currentlatitude);
let usersLocation = {
latitude: this.Currentlatitude,
longitude: this.Currentlongitude
};
console.log("usersLocation.latitude ",usersLocation.latitude);
locations.map((location) => {
let placeLocation = {
latitude: location.latitude,
longitude: location.longitude
};
location.distance = this.getDistanceBetweenPoints(usersLocation, placeLocation, 'km').toFixed(2);
});
return locations;
}
getDistanceBetweenPoints(start, end, units){
let earthRadius = {
miles: 3958.8,
km: 6371
};
let R = earthRadius[units || 'km'];
let lat1 = start.latitude;
let lon1 = start.longitude;
let lat2 = end.latitude;
let lon2 = end.longitude;
console.log("lon1 ",lat1); // here it gives me undefined
let dLat = this.toRad((lat2 - lat1));
let dLon = this.toRad((lon2 - lon1));
let a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(this.toRad(lat1)) * Math.cos(this.toRad(lat2)) *
Math.sin(dLon/2) *
Math.sin(dLon/2);
let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
let d = R * c;
return d;
}
toRad(x){
return x * Math.PI/180;
}
}
谢谢你的回复,我会测试,然后标记你的答案。我的问候 –
我注意到你使用的模型叫做“查询”,你能否给我提供示例代码,我非常感谢 –