Getting current location in ionic 3 problem


#1

im trying to use this function to get my current location:

getlocation(){
    let options = {
      timeout:10000,
      enableHighAccuracy:true
    };
    this.geolocation.getCurrentPosition(options).then((resp) => {
      console.log("inside func:",resp)
      return resp;
    });

inside the fuction i get my correct location howeve
and in ngOnInit when i call this function…

  ngOnInit(){
    console.log(this.getlocation())
}

my output is

undefined

can somebody tell me why?


#2

Because getlocation() doesn’t return anything. If you always declare return types for every function, you would have been told about this at compile time.


#3

Even so, i saved the value in a variable and returned and still get undefined, how can i fix this?


 getlocation(){
    let val;
    let options = {
      timeout:10000,
      enableHighAccuracy:true
    };
    this.geolocation.getCurrentPosition(options).then((resp) => {
      console.log("inside func:",resp)
      val = resp;
    });
return val;
  }

#4

i solved it by doing this:

  getlocation(){
    let val;
    let options = {
      timeout:10000,
      enableHighAccuracy:true
    };
    val = this.geolocation.getCurrentPosition(options).then((resp) => {
      console.log("inside func:",resp)
      return resp;
    });
  return val;
  }
 ngOnInit(){
   this.getlocation().then(val => {
      console.log(val)
    })

#5

Declare return types for all your functions, as I said before. The very first word of getlocation() should be return. As it is written, it is almost unreadable.


#6

Sorry I also need to interject. @rapropos is absolutely correct.

Just return the promise as a whole, your code is unnecessarily complicated.


#7

thanks but im still facing issues im trying to set longitude and latitude variables to the lat and long and i get from the function…

public long:Number;
public lat:Number;
  constructor(private geolocation: Geolocation,public loadingCtrl: LoadingController) {
  }
 getlocation(){

    let options = {
      timeout:10000,
      enableHighAccuracy:true
    };
     return this.geolocation.getCurrentPosition(options);
  }
  ngOnInit(){
    this.getlocation().then(resp => {
      this.long = resp.coords.longitude;
      this.lat = resp.coords.latitude;``
    });
    console.log(this.long);

when i console log i get it undefinded,


#8

MAN!!!

This will return nothing and rightly so…

console.log(this.long);

Coz it’ll be ran before your promise has completed.
Think of it like a callback.

For testing try this…

 ngOnInit(){
    this.getlocation().then(resp => {
      //just to prove it's working at all
      alert(resp.coords.longitude);
    });
    //FORGET THIS console.log(this.long);

If you want your screen to react to the presence of the latitude and longitude, make them observable, or just run a function after they’ve been populated…

ngOnInit(){
      this.getlocation().then(resp => {
      this.long = resp.coords.longitude;
      this.lat = resp.coords.latitude;
      this.someFunction(); //this.long and this.lat are now populated
    });

#9

thanks, i got it, took a small reading on this

now i came to a conclusion if i want a specific value to be returned as a promise i need to wrap in a promise like this…

  getlongitude(){

    let options = {
      timeout:10000,
      enableHighAccuracy:true
    };

    return new Promise((resolve =>{
      this.geolocation.getCurrentPosition(options).then(resp => {
        resolve(resp.coords.longitude);
      });
    } ))
  }

so i would consume it where ever i need, but just my last question, is there a better way or different way of writing this?


#10

If you’ve ever used a callback you’re 90% of the way with how promises work. Swim with the tide, not against it.

For any calling function you can write it like this…

async somethingToCallCoords(){
   var result = await getlongitude();
   console.log(result);
}

If you’re constantly wanting the latitude / longitude but don’t want to kill the mobile’s battery I’d suggest passing the values to a variable

 coords = {lat: 0, long: 0};

 ngOnInit(){
    this.getlocation().then(resp => {
      //just to prove it's working at all
      alert(resp.coords.longitude);
     this.coords= {lat: resp.coords.latitude, long: resp.coords.longitude};
    });

 someotherfunctionOffAButtonPress(){
  console.log(JSON.stringify(this.corrds));
 }

The first suggestion is probably easier for you to get on with.


#11

Absolutely.

getLongitude(): Promise<Number> {
  let options = {...};
  return this.geolocation.getCurrentPosition(options).then(rsp => rsp.coords.longitude);
}

You should never be typing “new Promise”.


#12

thanks so much guys <3


#13

Hi guys, I have this but getCurrentPositiondont do nothing:

  private getlocation() : Promise<Geoposition>{
        let val;
        let options = {
        timeout:10000,
        enableHighAccuracy:true
        };

        return this.geolocation.getCurrentPosition(options);
    }

 private loadMap(mapOptions: any) {
        this.getlocation().then( (position) => {
            this.latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
          });
}

Any idea?