How to Add Markers at the Tapped Locations in the .NET MAUI Maps (SfMaps)?
In the Syncfusion® .NET MAUI Maps control, you can add markers at tapped locations in the SfMaps through the following steps:
Step 1: Add the SfMaps control to your layout. Initialize the MapTileLayer to render the tiles returned from the Web Map Tile Services and set the URL to the UrlTemplate property, as shown in the following code sample.
XAML:
<map:SfMaps x:Name="map"> <map:SfMaps.Layer> <map:MapTileLayer x:Name="tileLayer" UrlTemplate="https://tile.openstreetmap.org/{z}/{x}/{y}.png"> </map:MapTileLayer> </map:SfMaps.Layer> </map:SfMaps>
Step 2: Add MapMarker to the MapTileLayer’s MapMarkerCollection, as shown in the following code sample.
XAML:
<map:MapTileLayer.Markers> <map:MapMarkerCollection> <map:MapMarker x:Name="marker" Latitude="-14.235004" Longitude="-51.92528" /> </map:MapMarkerCollection> </map:MapTileLayer.Markers>
Step 3: In the MapTileLayer.Tapped event, obtain the touch position and set the corresponding Latitude and Longitude to the marker’s Latitude and Longitude properties, as shown in the following code sample.
C#:
public class MapsBehavior : Behavior<ContentPage> { private MapTileLayer tileLayer; private MapMarker marker; protected override void OnAttachedTo(ContentPage bindable) { base.OnAttachedTo(bindable); this.tileLayer = bindable.FindByName<MapTileLayer>("tileLayer"); this.tileLayer.Tapped += TileLayer_Tapped; this.marker = bindable.FindByName<MapMarker>("marker"); } private void TileLayer_Tapped(object sender, Syncfusion.Maui.Maps.TappedEventArgs e) { var location = tileLayer.GetLatLngFromPoint(e.Position); marker.Latitude = location.Latitude; marker.Longitude = location.Longitude; } protected override void OnDetachingFrom(ContentPage bindable) { base.OnDetachingFrom(bindable); if (this.tileLayer != null) { this.tileLayer.Tapped -= TileLayer_Tapped; } this.tileLayer = null; this.marker = null; } }
Download the complete sample on GitHub.
Output:
Conclusion:
I hope you enjoyed learning how to add markers at the tapped locations in .NET MAUI Maps (SfMaps).
You can refer to our .NET MAUI Maps feature tour page to learn about its other groundbreaking feature representations. Explore our .NET MAUI Maps documentation to understand how to present and manipulate data.
For current customers, you can check out our .NET MAUI components from the License and Downloads page. If you are new to Syncfusion®, try our 30-day free trial to check out our .NET MAUI Maps and other .NET MAUI components.
Please let us know in the comments section if you have any queries or require clarification. Contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!