问题
I'm writing a Windows Phone app where I need to get user's location. I'm trying to this in a nice way (well as much as I can), using a separate class where I'm querying GeoCoordinateWatcher
for location data and return that data to calling method.
The problem is, I don't know how to return the the LocationData
struct to the calling method from the StatusChanged
event of the GeoCoordinateWatcher
. See the code & comments:
public struct LocationData
{
public string latitude;
public string longitude;
}
public class LocationService : GeoCoordinateWatcher
{
private GeoCoordinateWatcher watcher;
private LocationData StartLocationWatcher()
{
LocationData ld = new LocationData();
// The watcher variable was previously declared as type GeoCoordinateWatcher.
if (watcher == null)
{
watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
}
watcher.MovementThreshold = 20; // Use MovementThreshold to ignore noise in the signal.
watcher.StatusChanged += (o, args) =>
{
switch (args.Status)
{
case GeoPositionStatus.Ready:
// Use the Position property of the GeoCoordinateWatcher object to get the current location.
GeoCoordinate co = watcher.Position.Location;
ld.latitude = co.Latitude.ToString("0.000");
ld.longitude = co.Longitude.ToString("0.000");
//Stop the Location Service to conserve battery power.
watcher.Stop();
break;
}
};
watcher.Start();
return ld; //need to return this to the calling method, with latitude and longitude data taken from GeoCoordinateWatcher
}
}
回答1:
I'm not sure if this is what you're after.
Register the PositionChanged event:
you have to add an event listener to fire the fetching of the location
GeoCoordinateWatcher.PositionChanged += GeoCoordinateWatcherPositionChanged;
private void GeoCoordinateWatcherPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
var currentLatitude = e.Position.Location.Latitude;
var currentLongitude = e.Position.Location.Longitude;
}
More on when PositionChanged will fire.
来源:https://stackoverflow.com/questions/7438273/return-the-location-data-from-geocoordinatewatcher-statuschanged-event-in-window