Today I will tell you how to get reliable geolocation data on Cordova or Phonegap. It took me a lot of time to figure all this out, so I hope that I can save you some precious time with my article.
Note: I tested on Cordova 3.4.x and Android/WindowsPhone.
Before we start, make sure that you have
not installed the Cordova or Phonegap geolocation plugin! In case you already have, remove it with the following command "
cordova plugin remove org.apache.cordova.geolocation". We do not need this plugin since the native HTML5 support is much better! Further information can be found
here. I don't know why this plugin is still available in the official documentation... But don't worry if you come from Cordova or Phonegap, you don't have to change a lot in your existing code (maybe you have to eliminate the frequency attribute).
Please pay attention that, also when you are not using the geolocation plugin, you have to set the following privileges in your:
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
WPAppManifest.xml
<Capabilities>
<Capability Name="ID_CAP_LOCATION" />
</Capabilities>
The code for the implementation itself is relative trivial. I would suggest you to implement it after the following action plan:
- Before you do anything, check if geolocation is available (navigator.geolocation)
- Try to get the current position with high accuracy, if the request timed out or an error occur > fallback to lower accuracy.
Important parameter:
- enableHighAccuracy: true/false for high or low accuracy
- maximumAge: Accept a cached position whose age is no greater than the specified time in milliseconds. (Number)
- timeout: Maximum time of lenght in ms to get the position.
- frequency: Stop using this attribute. It is not W3C compliant. Use maximumAge instead!
Suggested values:
- enableHighAccuracy: true, maximumAge:3000, timeout: 5000
- enableHighAccuracy: false, maximumAge:3000, timeout: 30000
Tips:
- If you want to update your geolocation data continuously, use watchPosition(...) instead of getCurrentPosition(...). Also use the pause/resume functions of Cordova/Phonegap to start/stop the watch while the application is or return from background. The users battery will thank you.
- Keep in mind that the logic behind getCurrentPosition(...) and watchPosition(...) is differently on different devices. So test your implementation as much as you can!
Please let me know if this article helped you to improve your geolocation results. If you tested successfully with iOS drop a comment (ideal with required privileges) as well. Thanks!