Learning .NET MAUI – Part 13

In this post we’ll do three things:

  • Add a clear button to clear out the list of zip codes
  • Add the Connected service to make sure we have internet connection before trying to get the zip codes
  • Add the IMap service to show a map of a place

Clear Button

Starting easy, we can add a clear button to MainPage.xaml which will call a command to clear out the list.

            <Button
                Padding="10"
                Command="{Binding ClearCommand}"
                Text="Clear" />

The command is just going to empty the results which will cause the list to disappear. This method couldn’t be much simpler:

[ICommand]
async Task ClearAsync()
{
    Results.Clear();
}

Connectivity

It can be very useful and efficient to check whether the user has network connectivity before trying to go to a web service. To do this we declare the built-in platform interface IConnectivity. I chose to do this in the ZipCodeService, but of course I could have called this from the view model before invoking the service.

We declare the interface and then use Dependency Injection to inject it into the constructor and assign it to our local member.

IConnectivity connectivity;
HttpClient _httpClient;
public ZipCodeService(IConnectivity connectivity)
{
    _httpClient = new HttpClient();
    this.connectivity = connectivity;
}

We can now use that to check if the user has internet access

if (connectivity.NetworkAccess != NetworkAccess.Internet)
{
    await Shell.Current.DisplayAlert("No Internet", "Please check your internet connection", "OK");
    return null;
}

The only other step is to register in MauiProgram.cs

 builder.Services.AddSingleton<IConnectivity>(Connectivity.Current);
 builder.Services.AddSingleton<IMap>(Map.Default);

Notice I also registered the IMap service which we’ll look at next.

IMap

There are a number of ways to use the map. The two most common are to pass in a longitude and latitude or to pass in a placemark. Here is how you do it.

Create a button that will invoke ShowMapAsync (you can call it anything you like).

<Button
    Padding="10"
    Command="{Binding ShowMapCommand}"
    Text="Show Map" />

Next implement the command handler:

[ICommand]
public async Task ShowMapAsync()
{
    var placemark = new Placemark
    {
        CountryName = "United States",
        AdminArea = "MA",
        Thoroughfare = "Town Hall",
        Locality = "Acton"
    };
    var options = new MapLaunchOptions { Name = "Town Hall" };

    try
    {
        await Map.Default.OpenAsync(placemark, options);

    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
        await Shell.Current.DisplayAlert("Unable to open map", ex.Message, "OK");

    }
}

Let’s take this apart. First we create a placemark object. I’ve initialized it to find the town hall in Acton, MA. Create a MapLaunchOptions object that has the name of the place you are going to.

Call Map.Default.OpenAsync and pass in the placemark and options objects you created.

That’s it. When you press the button you added to Main the platform specific map program will open and with luck it will be pointing to the place you asked for.

The source for this post is here: https://github.com/JesseLiberty/LearningMauiPart10/tree/LearningMaui13

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in Essentials and tagged , . Bookmark the permalink.