Ionic 2, Geolocation undefined (attempt to data list by location)


#1

Hi,
So I’m trying to sort some data in a provider by Geolocation, I’ve been adapting the tutorial by Josh Morony.

I try to get Geolocation with the Ionic Native plugin, but it seems to return undefined. I want to only run the Promise resolving the data when there is a Latitude (lat) and longitude (lng) from the Geolocation returned. I’m most likely doing something very wrong, but when console.log’ing (this.lat) or (this.lng), I get undefined.

Here’s the attempt so far:
export class geoLocas {

    data: any;
    lat:any;
    lng:any;
    constructor(public http: Http, public zone:NgZone) {

    }
    getLocation(){
      let options: {timeout:10000, enableHighAccurary:true}
      Geolocation.getCurrentPosition(options).then(pos =>{
        this.zone.run(() => {
        let lat=pos.coords.latitude;
        let lng=pos.coords.longitude;
      });
        console.log("test",this.lat,this.lng)
      },
    (err) => {
      console.log("Geolocation error"+err);
    })
  }
    load(){
      this.getLocation();
      console.log(this.lat)
        if(this.data &&this.lat){
            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(location) {
....

Any help greatly appreciated, thank you!


#2

Are you waiting for the deviceready (aka Platform.ready) event to be fired. Until then, device interaction will not function properly.