Recently I have had to navigate through Xamarin.Forms Maps for a project.  After some documentation reading I found that XF Maps does not offer a lot of the customisation and functionality of the native map libraries (MapKit and Google Maps).  This left me having to write some custom renderers to complete the project’s requirements.

In this Xamarin how-to post, I will show you how to obtain the latitude, longitude and radius from the center of the map every time the user moves or zooms.  This is especially useful if you have dynamically updating pins.  Instead of bloating the map with 1000’s of pins, you will be able to show pins in the area of the map that is visible by the user.

Before getting busy with the custom renderers you must initialize and configure Xamarin.Forms Maps.  I highly recommend reading though the offical documentation here.

Shared Code

By inheriting from XFMaps we can create a custom event that will trigger every time the user moves the map and retrieve some custom arguments (latitude, longitude and radius).

iOS Custom Renderer (MapKit)

Here we will be subscribing to the RegionChanged event of the MKMapView to retrieve the updated coordinates and radius of the user and sending the information to our custom event that we created earlier. To calculate the radius from the current zoom level of the user we get the distance of the total visible longitude and latitude and determine which one is greater. We use the greater value in case the map is not square and are then still able to utilise the full view of the map.

Android Custom Renderer (GoogleMap)

The Android custom renderer is very similar to the iOS one, however we use the event CameraIdle of GoogleMaps and must wait to the map is ready before subscribing to the event. This event will trigger after the camera has finished moving. The radius is calculated with a similar method as iOS for consistency between platforms.

Using the Custom Control

The custom map can be set in initialised in xaml the same as the original XFMaps package. In the code behind we can subscribe to our custom event and perform any updates based on the users new location.

I hope this has helped everyone that needs this specific functionality. Please don’t hesitate contact or comment below with any questions.

The full source code is available here.