This recipe shows how to add an overlay to a map using the MapView control and the Overlay class
Recipe
- Create a new Xamarin.Android application named AddMapWithOverlay.
- Add a reference to the Mono.Android.GoogleMaps assembly.
- Obtain a Google Maps API key (see Obtaining a Google Maps API Key).
- Change the base class of Activity1 to Android.GoogleMaps.MapActivity and add an implementation for the abstract member, IsRouteDisplayed.
protected override bool IsRouteDisplayed { get { return false; } }
- Add a MapView to Main.axml using your Maps API key.
<com.google.android.maps.MapView android:id="@+id/mapWithOverlay" android:layout_width="fill_parent" android:layout_height="wrap_content" android:clickable="true" android:apiKey="Insert API Key here" />
- Add a class called MapOverlay that subclasses Android.GoogleMaps.Overlay with the following implementation to draw the overlay.
class MapOverlay : Overlay { GeoPoint _gp; public MapOverlay (GeoPoint gp) { _gp = gp; } public override void Draw (Android.Graphics.Canvas canvas, MapView mapView, bool shadow) { base.Draw (canvas, mapView, shadow); var paint = new Paint (); paint.AntiAlias = true; paint.Color = Color.Green; paint.Alpha = 50; var pt = mapView.Projection.ToPixels (_gp, null); float distance = mapView.Projection.MetersToEquatorPixels (200); canvas.DrawRect (pt.X, pt.Y, pt.X + distance, pt.Y + distance, paint); } }
- In the Activity’s OnCreate method, set the map’s center and zoom level and add the overlay to the map.
var map = FindViewById<MapView> (Resource.Id.mapWithOverlay); var gp = new GeoPoint ((int)42.3474410E6, (int)-71.0979440E6); map.Controller.SetZoom (19); map.Controller.SetCenter (gp); var overlay = new MapOverlay (gp); map.Overlays.Add (overlay);
Additional Information
The MapView class is part of the Google Add-On APIs. To use it in an emulator, the emulator must have these APIs included. Overlays can include custom drawn geometry, as shown in this recipe, as well as images or other controls. For more information see the Maps and Location document.
