Today, in a Windows Phone 7.5 “Mango” app, I needed to retrieve the phone’s most recent location and send it to a server from a background agent.
On this MSDN page, Microsoft suggests doing this by using the GeoCoordinateWatcher API:
This API, used for obtaining the geographic coordinates of the device, is supported for use in background agents, but it uses a cached location value instead of real-time data. The cached location value is updated by the device every 15 minutes.
Excellent. So how do we actually go about retrieving the latest cached location? I couldn’t find a code example of this anywhere. It would probably make sense for the API to have a static, no-hassle method that returns the cached location, but it doesn’t provide that.
The following code will return the latest available location (up to 15 minutes old):
private GeoPosition GetCachedLocation()
//Start a new watcher with default level of accuracy
geoWatcher = new GeoCoordinateWatcher();
//Get latest cached position
GeoPosition position = geoWatcher.Position;
Note that this method will execute even if you leave out geoWatcher.Start(); and geoWatcher.Stop();, which is what I tried at first, but then your location will contain empty values.
This satisfies my requirement. If you need some control over the provided accuracy, you could try creating your GeoCoordinateWatcher with a self-defined accuracy requirement using the GeoCoordinateWatcher(GeoPositionAccuracy) constructor, but I haven’t tested this. Since you can’t request a fresh location, perhaps it would simply return the latest available cached location that satisfies the given accuracy requirement?