0

My Ionic 3 weather app works correctly if I start with GPS enabled.

If I start the app with the GPS turned off, and having subscribed to listen to changes (see below watch.subscribe), although then manually enable it it does not recover latitude and longitude. I would like help please to control the GPS, that is, to "listen" to the on and off event, to be able to operate on that. Thank you!

this.geolocation.getCurrentPosition().then((resp) => {
this.global.latitude = resp.coords.latitude
this.global.longitude = resp.coords.longitude
  }).catch((error) => {
alert('Error getting location ' + error);
  });
  let watch = this.geolocation.watchPosition();
  watch.subscribe((data) => {
   this.global.latitude = data.coords.latitude
   this.global.longitude = data.coords.longitude
 });

1 Answer 1

0

It also happens that the behavior of the phone varies depending on the accuracy you have (example: in iOS, it's necessary to "true" in enableHighAccuracy).

I also had many issues with the location capability and ended up solving it as next:

create api.provider and inject into component:

-geo options declaration:

private geoOptions: GeolocationOptions = {
     enableHighAccuracy: true,
     timeout: 6000,
     maximumAge: 12000
};

-onInit called from constructor:

public onInit(): Promise<any> {
        return new Promise<any>((resolve: (value?: boolean | any) => void, reject: (reason?: any) => void) => {
       this.getCurrentPosition().subscribe((response: any) => {
           resolve(response);
       }, (err: any) => {
           reject(err);
       });
   });
}

-constructor that already handles getCurrentPosition errors and varies the accuracy options to call back before executing watchPosition:

constructor(public api: Api, private gps: Geolocation, private toast: ToastController) {
        const locationSubscription = this.isLocationActive.subscribe((response: any) => {
            const initExecute = () => {
                this.onInit()
                .then((val: any) => {
                    this.watchPosition().subscribe();
                    locationSubscription.unsubscribe();
                }).catch((reason: any) => {
                    // if fails, turn enableHighAccuracy options (some Android devices do not have HighAccuracy available)
                    this.geoOptions.enableHighAccuracy = !this.geoOptions.enableHighAccuracy;
                    initExecute();
                });
            };

            if (response && (response as boolean).toString().toLowerCase() === "true") {
                initExecute();
            }
        });
    }

-the currentPosition wrapped method:

 public getCurrentPosition(): Observable<Geoposition> {
        // Create an Observable that will start listening to geolocation updates
        // when a consumer subscribes
        return Observable.create((observer: Observer<Geoposition>) => {
            this.gps.getCurrentPosition(this.geoOptions).then((response: any) => {            // your todo validator
                // this.validateGeolocationResponse(err, observer, true);
            }).catch((err: any) => {
                // your todo validator
                // this.validateGeolocationResponse(err, observer, true);
            });
            // When the consumer unsubscribes, clean up data ready for next subscription.
            // return { unsubscribe() { navigator.geolocation.clearWatch(watchId); }};
        });
    }

-and finally, the watchPosition method:

public watchPosition(): Observable<Geoposition> {
        return Observable.create((observer: Observer<Geoposition>) => {
            this.gps.watchPosition(this.geoOptions).subscribe((response: any) => {
                // your validation method if coords are returned
                this.validateGeolocationResponse(response, observer);
            }, (err: any) => {
                // your validation method if coords are returned
                this.validateGeolocationResponse(err, observer, true);
            });
        });
    }

-Tip Create a ReplaySubject to store the last right coord values. It doesn't always return successfully, therefore it is advisable to search for the latest successes and return them to your subscriber if the current ones fail.

E.g.:

public currentLocation = new ReplaySubject<Geoposition>(2);

Blessings for you too!

2
  • Thank you ! Although the code appears difficult for my Ionic 3 level, I get to work Blessings to you
    – Guille
    Sep 27, 2019 at 12:04
  • Yes, I can understand you. But read it bit by bit. Intention commented each section for major understanding. Any questions, you can write me again. ;) (and rate the answer if it is useful: P). -Sincerely
    – 1antares1
    Sep 27, 2019 at 18:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.