The sample’s MapViewModel
class contains a GetLocation
method that uses the Geolocator
class, which is new to Windows Phone 8, to retrieve the phone’s current location (see Listing 18.1).
The GetPositionAsync
method is an awaitable method that allows you to retrieve the phone’s last known location without blocking the UI thread.
When attempting to call the Geolocator
object’s GetGeopositionAsync
method, if location is disabled in the phone’s settings, an UnauthorizedAccessException
is raised.
For more information on location tracking and the Geolocator
class, see Chapter 17, “Building Location Aware Apps.”
LISTING 18.1. MapViewModel.GetLocation
Method
async Task<GeoCoordinate> GetLocation()
{
var geolocator = new Geolocator();
Geoposition geoposition;
try
{
geoposition = await geolocator.GetGeopositionAsync();
}
catch (UnauthorizedAccessException)
{
MessageService.ShowMessage(
"Location is disabled in the phone settings.");
return center;
}
Geocoordinate geocoordinate = geoposition.Coordinate;
return geocoordinate.ToGeoCoordinate();
}
The MapViewModel
class sets its Center
property to the value returned by the GetLocation
method, as shown:
async void CenterMapOnLocation()
{
Center = await GetLocation();
Location = center;
ZoomLevel = 8;
}
MapView.xaml contains an AppBarIconButton
that, when tapped, executes the viewmodel’s CenterMapOnLocationCommand
, which calls the CenterMapOnLocation
method.
18.116.63.231