January 6, 2018
  • All

Testing Geolocation on Android

Max Lynch

CEO

We receive a large number of bug reports about Geolocation not working on Android. In fact, we at Ionic often run into the same issues and get worried that we’ve broken something.

Fear not, these issues are actually not due to Ionic or Cordova, but quirks in how the Android emulator sends Geolocation data for testing.

Sending Coordinates

In the emulator, you must open the Extended controls from the emulator menu, and manually “Send” coordinates to the emulator. The Extended controls can be found in this menu next to the Emulator window:

One “Send” will be consumed by one turn of getCurrentPosition or watchPosition, meaning that, for a watch, you have to send a coordinate for each position you’d want to return from watchPosition. If you don’t, then only the first call will work, the next will fail!

One easy way to test watchPosition is to find a GPX file and load it in the emulator. That will walk through each position and send it to the emulator. Here’s one that could work.

Required options

Finally, you must provide arguments to the options field, otherwise calls can fail. In particular, it seems the most important field that must be provided is timeout. Here’s an example that uses a 30 second timeout:

navigator.geolocation.getPosition(success, error, { timeout: 30000 });

Or with Ionic Native:

this.geolocation.getCurrentPosition({ timeout: 30000 });

Conclusion

Android is finicky when it comes to testing Geolocation. Make sure you’re using the Emulator Extended Controls to send Geolocation coordinates, and supply default options to the call. Without keeping these in mind, Geolocation calls may fail or never return!


Max Lynch

CEO