Xamarin Forms Maps... but Better
Maps for 🤖 & 🍎
I use maps in a couple of my own projects, both of which use custom pin icons. Unfortunately, the default Xamarin.Forms.Maps package doesn’t support this out of the box. Originally, I was using Xamarin.Forms.GoogleMaps, which is fantastic but I wanted something that used the native mapping control on each platform (Android & iOS) while providing similar features.
I based my “better” maps package off Xamarin.Forms.Maps
, so it’s mostly a drop in replacement, besides a namespace change to Xamarin.Forms.BetterMaps
.
Pin
The below properties have been added,
ImageSource
, of type ImageSource, the source of the pin iconTintColor
, of type Color, tint colour to apply to the pin icon- ignored if Transparent
Anchor
, of type Position, the anchor point for the pin icon- (0, 0) denotes the centre
- -1 ≤ x ≤ 1 & -1 ≤ y ≤ 1
ZIndex
, of type int, the stack order of the pin (higher is given precedence)
Additionally, if you’re using TintColor
, you should implement IMapCache
and pass it into the .Init
call in each platform. This will prevent the same pin icon getting the same tint applied multiple times, which can become expensive.
Map
The below properties have been added,
MapTheme
, of type MapTheme, the theme of the map (either System, Light or Dark)ShowUserLocationButton
, of type bool, whether to display the button to track the user’s locationShowCompass
, of type bool, whether to display the compassSelectedPin
, of type Pin, the currently selected pin
The below events have been added,
SelectedPinChanged
, event is fired when the selected pin has changedMarkerClicked
, event is fired when a pin is tappedInfoWindowClicked
, event is fired when the information window is tappedInfoWindowLongClicked
, event is fired when the information window is long tapped
You’ll need to setup map themes on Android by creating two map style files (one for light & dark) using mapstyle.withgoogle.com. Once created add the styles to the Assets
folder in your Android project and register the filenames after the call to .Init
in the MainActivity.cs
. For iOS there is no setup required, it will use the in-built light & dark map themes.
public override void OnCreate(Bundle savedInstanceState)
{
...
Xamarin.FormsBetterMaps.Init(this, savedInstanceState);
...
Xamarin.FormsBetterMaps.SetLightThemeAsset("your.light.style.json");
Xamarin.FormsBetterMaps.SetDarkThemeAsset("your.dark.style.json");
...
}
You’ll notice the Pin event handlers have been moved up to the Map, this simplifies the renderer logic by removing the need to manage events for each pin individually.
Hopefully this helps you out the next time you need a mapping control with custom pins! If you run into any trouble please feel free to raise an issue on GitHub, PRs are also welcome!