I am new to Ionic 2 and following some tutorials.
In this case I need to change following method:
applyHaversine(locations){
let usersLocation = {
lat: 40.713744,
lng: -74.009056
};
locations.map((location) => {
let placeLocation = {
lat: location.latitude,
lng: location.longitude
};
location.distance = this.getDistanceBetweenPoints(
usersLocation,
placeLocation,
'miles'
).toFixed(2);
});
return locations;
}
You can see that variable usersLocation is hard-coded:
let usersLocation = {
lat: 40.713744,
lng: -74.009056
};
I would like to get there the real user location.
I have seen the method Geolocation.getCurrentPosition(), but I don´t know how to implement it in this case.
Thank you
EDITED
applyHaversine(locations){
Geolocation.getCurrentPosition().then((resp) => {
let latitud = resp.coords.latitude
let longitud = resp.coords.longitude
}).catch((error) => {
console.log('Error getting location', error);
});
console.log(this.latitud);
let usersLocation = {
lat: this.latitud,
lng: this.longitud
};
I would use the Geolocation cordova plugin. You can access it with
ionic-native
. First you need to install the plugin:You can then use it like this:
https://ionicframework.com/docs/v2/native/geolocation/
EDIT:
Your updated code is almost correct. You made 2 small mistakes in your code:
You defined 2 local variables (
let latitud
andlet longitud
), but then later in your code you access them by usingthis.latitud
andthis.longitud
.this
always refers to variables defined in your class, so those will be undefined. You either have to use local variables or class wide variables, but that depends on your architecture. Both work.Geolocation.getCurrentPosition()
returns a promise. This means that the code inside.then(() => {})
will be executed later (as soon as the plugin has the result with your location). But the rest of your code is outside thethen
, which means that it will be executed before you have the location. So you need to copy your whole code into thethen
like this:EDIT 2:
A working example would be:
And where you use this function: