Search code examples
.netmapsmaui

How can I determine which Pin was clicked in a .Net Maui map?


I've added a map to my application. Since pins can only take Location, address and label. I don't really know which pin was clicked. I could probably use address or location to crawl though my data list and figure out which one was mapped to that pin. But is there a way to add an ID, like my database ID, to quicky get the data record associated with the pin? There is an Id property on the pin that is inherited but that is a GUID that is created behind the scenes.

The pins are created with a data template, so they appear as my data list grows. I would like to be able to take the use to a more detailed page about the location they clicked on.

This is the map XAML with the data template:

<maps:Map x:Name="map" MapClicked="OnMapClicked" ItemsSource="{Binding Positions}">
    <maps:Map.ItemTemplate>
        <DataTemplate>
            <maps:Pin Location="{Binding Location}" 
                      Address="{Binding Address}" 
                      Label="{Binding Description}" 
                      InfoWindowClicked="OnInfoClicked" 
                      MarkerClicked="OnMarkerClicked"/>
        </DataTemplate>    
    </maps:Map.ItemTemplate> </maps:Map>

Solution

  • This is the handler that retrieves the original record using the BindingContext.

    async void OnMarkerClicked(object sender, PinClickedEventArgs args)
    {
        Pin p = (Pin)sender;
    
        Position pos = (Position)p.BindingContext;
        Console.WriteLine($"OnMarkerClicked: {pos.ID}");
    }