Cross Platform C#

iOS and Android Mapping with Xamarin.Forms

Mobile devices need mapping as much as cars need wheels. Here's how to add mapping to your iOS and Android development via Xamarin.Forms.

Maps are one of the important features of mobile devices. They put context to data. With them, users can see the location of a store, what the local weather looks like or how close they are to a bar. Unfortunately, the cross-platform nature of Xamarin.Forms means that developers need a cross-platform mapping API to display maps and the points on the maps. This article will take a look at mapping with Xamarin.Forms.

Note: Maps have been a favorite topic of this column, so you'll definitely see earlier coverage of it for iOS and Android. If you search the magazine's archives, lots of it is still relevant. This article updates some of the information that's been published before.

Setup
Developers who have dealt with mapping in iOS know how easy it is. Android developers, not so much. Unfortunately, Android developers must go through a series of steps to get support for maps. This includes getting Google Play services up-to-date, getting a Google Maps key and such.

Note: To work through creating Android mapping setup for maps v2, walk through the "Obtaining a Google Maps API Key" guide on the Xamarin Web site.

Once the Android platform is set up, the user must perform an initialization of Xamarin.Forms.Maps through the following steps:

  • Download the latest version of Xamarin.Forms.Maps from NuGet.
  • In the FinishedLaunching event in AppDelegate.cs file in iOS, add the following command, after the call to Xamarin.Forms.Init();: Xamarin.FormsMaps.Init();
  • In the Android project in the OnCreate event, add the following command after the call to Xamarin.Forms.Init(this, bundle);: Xamarin.FormsMaps.Init(this, bundle);

Map It
Mapping is fairly simple. In this example, the Map view is a control that the developer will interact with. The map view is placed onto a ContentPage. The ContentPage is placed within a NavigationPage, and the NavigationPage is set as the MainPage of the application. Now, let's look at the code in Listing 1:

Listing 1: The Mapping App's Main Page and Navigation
public class App : Application
{
  MapPage content;
  public App()
  {
    content = new MapPage();
    MainPage = new NavigationPage(content);
     content.Title = "Map";
  }

  async protected override void OnStart()
  {
    var pos = await GetPosition();
    content.pos = pos;
  }
  async private System.Threading.Tasks.Task<Position> GetPosition()
  {
    var gc = new Geocoder();
    var pos = await gc.GetPositionsForAddressAsync("118 Durwood Rd., Knoxville, TN 37922");
    var ret = pos.First();
    return ret;
  }

}
public class MapPage : ContentPage
{
  private Position _pos;
  private Map _map;
  public Position pos {
    get
    {
      return _pos;
    }
    set {
      _pos = value;
      _map.MoveToRegion(new MapSpan(_pos, .2, .2));
    } }
  public MapPage()
  {
    _map = new Map();
    _map.MapType = MapType.Street;
    var item = new Pin();
    item.Label = "Wally's Office";
    item.Position = new Position(35.899856, -84.123031);
    item.Address = "118 Durwood Rd.";
    item.Clicked += Item_Clicked;
    item.Type = PinType.SavedPin;
    _map.Pins.Add(item);
    var stack = new StackLayout { Spacing = 0 };
    stack.Children.Add(_map);
    Content = stack;
  }
  private void Item_Clicked(object sender, EventArgs e)
  {
    System.Diagnostics.Debug.WriteLine("Item clicked.");
  }
}

The basics of this code are that it performs the following items:

  • A Map view is created.
  • The MapType property is set. This is an enum. It can have values that are street, satellite, and hybrid.
  • A pin is created and is added to the map instance. Several properties are set on the pin. One of the interesting properties is the Clicked property. When the content of the pin is opened, and a user touches/clicks the pin, the pin's Click event is fired. In this specific example, the output is directed at the debug window in Visual Studio.
  • Once the map is created, it's added to a StackLayout. The StackLayout instance is added to the content of ContentPage.
  • The ContentPage is placed within a NavigationPage, and the NavigationPage is added to the MainPage.
  • Finally, the map is displayed to a user.

Geocoding
Addresses are what people think of when using a map. Unfortunately, computers aren't very good with addresses; they work much better with numbers. Thankfully, there's a technology that allows for the conversion between the two. That technology is referred to as geocoding. Xamarin.Forms contains a geocoder that can be used to convert from an address to a latitude/longitude coordinate. This process is called geocoding, or forward geocoding. Converting from a latitude/longitude pair to an address is the opposite and is referred to as reverse geocoding. The Xamarin.Forms geocoder allows a developer to perform forward and reverse geocoding.

Returning to the code in Listing 1, look at the OnStart method in the App class. Here's what's happening in this method:

  • An instance of the geocoder class is created.
  • The method GetPositionsForAddressAsync performs a basic forward geocode.
  • Notice that the forward and reverse geocoding are async/await APIs. The geocoder class calls the platform-specific API for geocoding. This will require an Internet connection, so it makes sense that the method is asynchronous.
  • There are multiple latitude/longitude positions that are returned. In this example, the program uses just the first one.
  • The first position is passed to the map page and then to the map instance. The map is then centered on the point that's provided.

The result of all of these operations in Listing 1 is the output in Figure 1 (in the Android Genymotion Emulator) and Figure 2 (iPhone simulator on a Mac).

[Click on image for larger view.] Figure 1. Map App on an Android Genymotion Emulato
[Click on image for larger view.] Figure 2. Map App on an iPhone Simulator Running on a Mac

About the Author

Wallace (Wally) B. McClure has authored books on iPhone programming with Mono/Monotouch, Android programming with Mono for Android, application architecture, ADO.NET, SQL Server and AJAX. He's a Microsoft MVP, an ASPInsider and a partner at Scalable Development Inc. He maintains a blog, and can be followed on Twitter.

.NET Insight

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.

Upcoming Events