Geolocation buggy in Capacitor 4, SDK 32

I’ve been using the same simple function to get user location for several versions now and after upgrading to Capacitor 4, it is very unreliable. It returns an error the first time, returns a position the second time, an error the third time, and so on.

Error: location unavailable

Is there something I’m missing here? What changed in Capacitor 4 and/or SDK 32?

  getUserLocation() {
    return new Promise((resolve) => {
      Geolocation.getCurrentPosition().then(
        (position) => {
          this.userLocation = {
            lat: position.coords.latitude,
            lon: position.coords.longitude,
          };
          this.isLocationAware(true);
          resolve(this.userLocation);
        },
        (_err) => {
          this.isLocationAware(false);
          this.userLocation = false;
          resolve(this.userLocation);
        }
      );
    });
  }
Ionic:

   Ionic CLI                     : 6.20.1 (/Users/---/.nvm/versions/node/v14.19.2/lib/node_modules/@ionic/cli)
   Ionic Framework               : @ionic/angular 6.1.2
   @angular-devkit/build-angular : 13.3.3
   @angular-devkit/schematics    : 13.0.4
   @angular/cli                  : 13.0.4
   @ionic/angular-toolkit        : 6.1.0

Capacitor:

   Capacitor CLI      : 4.1.0
   @capacitor/android : 4.1.0
   @capacitor/core    : 4.1.0
   @capacitor/ios     : 4.1.0

Utility:

   cordova-res : 0.15.4
   native-run  : 1.7.0

[info] Found 8 Capacitor plugins for android:
       @capacitor/app@4.0.1
       @capacitor/device@4.0.1
       @capacitor/geolocation@4.0.1
       @capacitor/haptics@4.0.1
       @capacitor/keyboard@4.0.1
       @capacitor/share@4.0.1
       @capacitor/splash-screen@4.0.1
       @capacitor/status-bar@4.0.1

Where in your component is this method being called?

getUserLocation is used in several places but is initially called in app.component.ts on startup. I’d share some more specific code but it would be hard to encapsulate without sharing several related components (it is not called directly). It works in SDK 30 and older (I haven’t tested 31 at this point). When I pull to refresh, it works exactly 50% of the time.

Ok, after tooling around with this issue, it seems it might have had something to do with the emulator. I wiped user data and reinstalled the app. Seems to work just fine now.

1 Like