Agile App Co. Ltd

developer@agileapp.co | 01273 782444

Moving / Updating A Map Pins Location in Xamarin Forms Maps

How to continuously update a custom map pin location on a map using Xamarin Forms Maps.

Wow, we thought this was going to be impossible!! Using Xamarin Forms trying to get our own map pin image on the map was one thing but then getting the location to update without having to clear all the pins was a challenge!! 

1. Follow the Xamarin Tutorial to get your custom map pins going! https://developer.xamarin.com/guides/xamarin-forms/custom-renderer/map/

2. After updating your pins in the forms project, call a messaging centre to run some code natively 

MessagingCenter.Send<CustomerMapPage, FocusEventArgs>(this, Messages.UpdatedPins, e);

3. Subscribe to your messaging centre and adjust the pins

 
             MessagingCenter.Subscribe<CustomerMapPage, List<Position>>(this, VanuseApp.Helpers.Messages.HighlightTripOnPlatform, (sends, arg) =>
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                   
                    FormsMap_PinsUpdated(this, null);
                });
 
 
            });
 
        private void FormsMap_PinsUpdated(object sender, EventArgs e)
        {
 
            customPins = formsMap.CustomPins;
 
            if (nativeMap != null && nativeMap.Annotations != null && nativeMap.Annotations.Count() > 0)
            {
                foreach (var a in nativeMap.Annotations)
                {
                    var title = a.GetTitle();
                    if (!string.IsNullOrEmpty(title))
                    {
                        var pin = customPins.FirstOrDefault(p => p.Pin.Label == title);
                        if (pin != null)
                            a.SetCoordinate(new CLLocationCoordinate2D { Latitude = pin.Pin.Position.Latitude, Longitude = pin.Pin.Position.Longitude });
 
                    }
                }
 
                nativeMap.SetNeedsDisplay();
            }
            
        }
4. Make sure the customPins property is observable 
 private ObservableCollection<CustomPin> customPins;
        public ObservableCollection<CustomPin> CustomPins
        {
            get
            {
                if (customPins == null)
                {
                    customPins = new ObservableCollection<CustomPin>();
                }
                return customPins;
            }
            set { customPins = value; }
        }
 

 

Leave a Comment

Scroll to Top