0

I want to know the user's location when they press on a certain button and push it to the database to a certain table with the user id.

How can I do this in IONIC 5?

Matus Dubrava
  • 13,637
  • 2
  • 38
  • 54
esraa
  • 1
  • 1
  • Do you mean Ionic 5? It's only out in beta. For support we go by the framework version which is currently Ionic 4. There is a Ionic CLI at v5 but that's not the framework version you should be mentioning when requesting support. – rtpHarry Dec 23 '19 at 11:37

1 Answers1

0

Welcome to Stackoverflow!

Have you tried '@ionic-native/geolocation' and Google Maps API? You can do something like this:

1 - Get the current location. We have two variables: latitude and longitude

getCurrentLocation() {    

    let options = {timeout : 10000 , enableHighAccuracy:true};
    let locationObs = new Observable(observable => {
      this.geolocation.getCurrentPosition(options)

      .then(resp => {

        this.latitude =  resp.coords.latitude
        this.longitude = resp.coords.longitude                

        let location = new google.maps.LatLng(this.latitude, this.longitude);
        observable.next(location);                


      }).catch( error => {             

        loading.dismiss(); 
        return false;
      })
    })

    return locationObs;
  }  

2 - Call the function when the button is clicked. To prevent memory leaks, use unsubscribe after you get the location:

buttonClicked(){   

      let sub = this.getCurrentLocation().subscribe(location => {
           console.log(this.latitude, this.longitude)
           sub.unsubscribe()
      })       
  }  

Let me know if you have more questions.

Diego Desenvolvedor
  • 378
  • 1
  • 6
  • 22
  • Is there a reason for using an observable in this snippet? If so, then it will need to be unsubscribed as well to prevent memory leaks. – rtpHarry Dec 23 '19 at 11:36
  • In my case, I need the exact location of the user, so the observable it's very useful here. And yes, the unsubscribe is necessary... I've edited the response.. thank you.. – Diego Desenvolvedor Dec 23 '19 at 14:33
  • Thank you so much for replying. Now i want my button to do two functions the first is fetching the location and the second is to go the page. i read that you cant do two functions . Start . can you help me what should i do? – esraa Dec 25 '19 at 06:12
  • i have tried what you gave me i added the import in the providors page and in the page i want the button which is home import { Geolocation } from '@ionic-native/geolocation/ngx'; also in the html Start but when i click on the start the following error comes up https://prnt.sc/qfg788 – esraa Dec 25 '19 at 07:18
  • You are right, it's possible to use two functions on the same button tag. Check this: https://stackoverflow.com/a/52352202/7907226 .About the error, you have to import the observable, like this: Add this: import { Observable } from 'rxjs/Observable' – Diego Desenvolvedor Dec 25 '19 at 13:24