Xamarin Forms Map Center

Problem:

I have been working on an app in Xamarin, with the goal of being able to deploy to UWP, Android and IOS. This is my first real effort with Xamarin, and the first time publishing IOS and Android to their respective stores. Actually, this is my first IOS app ever! I still need to get on to Craigslist and find a reasonably priced Mac Mini so that I can build the IOS app.

Some app background: it makes use of the map control. My needs aren’t too difficult, but I need to know what the map control is displaying at any given moment. Specifically, I need the latitude and longitude of the map center. At least at this point, my app doesn’t need to worry about location tracking.

I am going to use Xamarin forms and take advantage of the cross platform UI. I also want to make use of the MVVM pattern and the data binding associated with XAML.I will of course use my favorite MVVM framework: Prism (I am going to do a series on Prism and UWP and a series on Prism and Xamarin Forms as well at some point). All of this sounds great: but unfortunately the map center data structure isn’t exposed as a bindable property, so we can’t use it directly in our view model.

Well, since every C#/XAML blog person needs an attached property post, that is what I decided to do. I am not sure that it is the best solution, but I can say that it seems to be working for me right now. Look for an update on this post if it doesn’t!

Solution:

I decided I wanted two properties. One that turned the tracking on and off and one that stored the information about what the map was viewing.

Attached properties are all kind of the same, so first we will just setup the basics (if you need a bit of a refresher on attached properties, check out the Xamarin docs):

  • Creation
  • Getter/Setter
  • Change event
public static class MapCenterProperty
{
	public static readonly BindableProperty CenterProperty =
		BindableProperty.CreateAttached(
			"Center",
			typeof(MapSpan),
			typeof(MapCenterProperty),
			null,
			propertyChanged: OnCenterChanged);

	public static MapSpan GetCenter(BindableObject view)
	{
		return (MapSpan) view.GetValue(CenterProperty);
	}

	public static void SetCenter(
		BindableObject view, MapSpan mapSpan)
	{
		view.SetValue(CenterProperty, mapSpan);
	}

	private static void OnCenterChanged(
		BindableObject view, object oldValue, object newValue)
	{
	}

	public static readonly BindableProperty TrackCenterProperty =
		BindableProperty.CreateAttached(
			"TrackCenter",
			typeof(bool),
			typeof(MapCenterProperty),
			false,
			propertyChanged: OnTrackCenterChanged);

	public static bool GetTrackCenter(BindableObject view)
	{
		return (bool) view.GetValue(TrackCenterProperty);
	}

	public static void SetTrackCenter(
		BindableObject view, bool value)
	{
		view.SetValue(TrackCenterProperty, value);
	}

	private static void OnTrackCenterChanged(
		BindableObject view, object oldValue, object newValue)
	{
	}
}

So let’s take a look at the TrackCenterProperty first. This is the one that is used to toggle the tracking off and on. The important stuff happens in the OnTrackCenterChanged event: it sets up the tracking. If the old value is false and the new value is true, start tracking. Stop tracking if the reverse is true.

Now it would be great if the Map control had an event that fired when the view of the map changed, but it doesn’t. So that is a bit of an issue. Luckily there is a bit of a hack we can use. We are interested in when the “VisibleRegion” property changes. So we are going to subscribe to the “PropertyChanged” event instead. If the name of the property being changed is “VisibleRegion”, we want to know about it.

Let’s update the OnTrackCenterChanged method from up above to subscribe and unsubscribe depending on the value of TrackCenter. It could look like the following:


private static void OnTrackCenterChanged(
	BindableObject view, object oldValue, object newValue)
{
    Map map = view as Map;
    if (map == null)
        return;

    bool ov = (bool) oldValue;
    bool nv = (bool) newValue;

    if (ov && !nv)
    {
        /// was true, now false, unsubscribe
        map.PropertyChanged -= OnMapPropertyChanged;
    }
    else if (!ov && nv)
    {
        /// was false, now true, subscribe
        map.PropertyChanged += OnMapPropertyChanged;
    }
}

All we are doing is subscribing or unsubscribing to the PropertyChanged event depending on the value of TrackCenter. Below is the event handler for that event. The only thing it really does is check to see if it is the VisibleRegion property being changed and if so, update the value of the CenterProperty.


private static void OnMapPropertyChanged(
	object sender, PropertyChangedEventArgs a)
{
    Map map = sender as Map;
    if (map == null)
        return;

    if (a.PropertyName == "VisibleRegion"
        && map.VisibleRegion != null)
    {
        Debug.WriteLine("SetCenter");
        map.SetValue(CenterProperty, map.VisibleRegion);
    }
}

Now all we have to do is setup the OnCenterChanged event. The only thing we have to be concerned about is giving ourselves a bit of fuzziness on whether the center point is changed enough to update the map, otherwise I found that the center point property was being updated too often.

private static void OnCenterChanged(
    BindableObject view, object oldValue, object newValue)
{
    var map = view as Map;
    if (map == null)
        return;

    MapSpan newview = newValue as MapSpan;
    MapSpan oldView = oldValue as MapSpan;

    if (newview != null &&
        !Util.MapSpanHelper.IsEqual(oldView, newview))
    {
        map.MoveToRegion(newview);
        SetCenter(view, newview);
    }
}

And the helper function for checking if the MapSpan has changed enough:

public static class MapSpanHelper
{
    public static bool IsEqual(double d1, double d2)
    {
        double dif = Math.Abs(d1 * 0.00001);
        return (Math.Abs((d1 - d2)) <= dif);
    }

    public static bool IsEqual(MapSpan ms1, MapSpan ms2)
    {
        if (ms1 == null && ms2 == null)
            return true;
        else if (ms1 == null || ms2 == null)
            return false;
        else if (
            IsEqual(ms1.Center.Latitude, ms2.Center.Latitude)
            && IsEqual(ms1.Center.Longitude, ms2.Center.Longitude)
            && IsEqual(ms1.LatitudeDegrees, ms2.LatitudeDegrees)
            && IsEqual(ms1.LongitudeDegrees, ms2.LongitudeDegrees))
            return true;
        else
            return false;
    }
}

You can adjust the fuzziness as appropriate.

Finally, we can setup our XAML and view model. Remember to add the namespaces. The MapCenterProperty class exists in the “Demo.Views” assembly.


xmlns:maps="clr-namespace:Xamarin.Forms.Maps;assembly=Xamarin.Forms.Maps"

xmlns:loc="clr-namespace:Demo.Views;assembly=Demo"

<maps:Map MapType="Street" loc:MapCenterProperty.TrackCenter="True" loc:MapCenterProperty.Center="{Binding Center,Mode=TwoWay}">

</maps:Map>

And the view model:


/// BindableBase provided by Prism, implements the
/// INotifyPropertyChanged interface for the view model
/// and some helper functions
public class DemoViewModel : BindableBase
{
    // ...

    private MapSpan _center = null;
    public MapSpan Center
    {
        get { return _center; }
        set { SetProperty<MapSpan>(ref _center, value); }
    }
}

And there we have it. We now have the viewable region of the map control bound to our view model. From within the view model we can change what is being shown on the map simply by setting the Center property. In the case of my app, I am also going to make use of the GeoLocator plugin from James Montemagno to provide some pretty nice location services to go with the maps in my app.

Hopefully you found this useful.


3 comments

  1. Pingback: Xamarin Forms Maps Bits – random bits and bytes


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s