Using the location service on the new entry page

Now that we have an interface that defines our location service, we can use it in the core project of our TripLog app. The main place we will need to capture location in the app is on the new entry page, so coordinates can be attached to log entries when they are added. Since we want to keep our app logic separate from the user interface, we will use the location service in the new entry page's ViewModel, and not on the page itself.

In order to use the ILocationService interface in the NewEntryViewModel, perform the following steps:

  1. First, add a read-only property to the NewEntryViewModel to hold an instance of the location service:
      public class NewEntryViewModel : BaseViewModel
{
readonly ILocationService _locService;

// ...
}
  1. Next, update the NewEntryViewModel constructor to take an ILocationService instance, and set its read-only ILocationService property:
      public NewEntryViewModel(INavService navService, 
ILocationService locService
)
: base(navService)
{
_locService = locService;
Date = DateTime.Today;
Rating = 1;
}
  1. Finally, update the NewEntryViewModel Init() method to use the location service to set the Latitude and Longitude double properties:
      public override async Task Init()
{
var coords = await _locService.GetGeoCoordinatesAsync();
Latitude = coords.Latitude;
Longitude = coords.Longitude;
}

Notice how we can completely work with the location service in the ViewModel, even though we haven't actually written the platform-specific implementation. Although, if we were to run the app, we would get a runtime error because the implementation doesn't actually exist, but it's useful to be able to work with the service through abstraction to fully build out and test the ViewModel.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.48.181