Getting started with MAUI Maps (SfMaps)

5 Jul 202224 minutes to read

This section explains the steps required to add the maps control with the shape layer and its elements such as data labels, tooltip, markers, and legends. This section covers only basic features needed to know to get started with Syncfusion maps.

Creating an application using the .NET MAUI Maps

  • Create a new .NET MAUI application in the Visual Studio.

  • Syncfusion .NET MAUI components are available on nuget.org. To add SfMaps to your project, open the NuGet package manager in Visual Studio, search for [Syncfusion.Maui.Maps] then install that.

Register the handler

Syncfusion.Maui.Core NuGet is a dependent package for all Syncfusion controls of .NET MAUI. In the MauiProgram.cs file, register the handler for Syncfusion core.

  • ~/MauiProgram.cs
  • using Microsoft.Maui;
    using Microsoft.Maui.Hosting;
    using Microsoft.Maui.Controls.Compatibility;
    using Microsoft.Maui.Controls.Hosting;
    using Microsoft.Maui.Controls.Xaml;
    using Syncfusion.Maui.Core.Hosting;
    
    namespace MyProject
    {
        public static class MauiProgram
        {
            public static MauiApp CreateMauiApp()
            {
                var builder = MauiApp.CreateBuilder();
                builder
                .UseMauiApp<App>()
                .ConfigureSyncfusionCore()
                .ConfigureFonts(fonts =>
                {
                    fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                });
    
                return builder.Build();
            }
        }
    }

    Adding namespace

    Add the following namespace.

    xmlns:map="clr-namespace:Syncfusion.Maui.Maps;assembly=Syncfusion.Maui.Maps"
    using Syncfusion.Maui.Maps;

    Initializing maps

    Create an instance for the maps control, and add it as content.

    <map:SfMaps>
      
    </map:SfMaps>
    SfMaps map = new SfMaps();
    	
    this.Content = map;

    Set GeoJSON data or shapefile for shape layer from various source

    The Layer in SfMaps holds MapShapeLayer. The actual geographical rendering is done in the each MapShapeLayer. The ShapesSource property of the MapShapeLayer is of type MapSource. The ShapesSource can be set as the .json source or shapefile.

    IMPORTANT

    The Mercator projection is the default projection in the maps.

    The ShapesSource property is used to load shapes from different sources:

    • FromFile returns a MapSource that reads a shape source from a local file.
    • FromUri returns an MapSource that downloads and reads a shape source from a specified URI.
    • FromResource returns a MapSource that reads a shape source file embedded in an assembly.
    • FromStream returns a MapSource that reads a shape source from a stream that supplies source data.

    Loading a local file

    SfMaps provides support to load the json data or shapefile from local path.

    public MainPage()
    {
        InitializeComponent();
        SfMaps map = new SfMaps();
        MapShapeLayer layer = new MapShapeLayer();
        layer.ShapesSource = MapSource.FromFile(@"D:\MyProject\usa_state.shp");
        map.Layer = layer;
        this.Content = map;
    }

    The MapSource.FromFile method requires a string argument, and returns a new MapSource object that reads the data from the shape source file. There’s also an implicit conversion operator that enables the filename to be specified as a string argument to the ShapesSource property

    <map:SfMaps>
        <map:SfMaps.Layer>
            <map:MapShapeLayer ShapesSource="D:\MyProject\usa_state.shp" />
        </map:SfMaps.Layer>
    </map:SfMaps>
    public MainPage()
    {
        InitializeComponent();
        SfMaps map = new SfMaps();
        MapShapeLayer layer = new MapShapeLayer();
        layer.ShapesSource = MapSource.FromFile(@"D:\MyProject\usa_state.shp");
        map.Layer = layer;
        this.Content = map;
    }

    Load a remote file

    SfMaps provides support to load the json data or shapefile from the uri.

    public MainPage()
    {
        InitializeComponent();
        SfMaps map = new SfMaps();
        MapShapeLayer layer = new MapShapeLayer();
        layer.ShapesSource = MapSource.FromUri(new Uri("https://cdn.syncfusion.com/maps/map-data/world-map.json"));
        map.Layer = layer;
        this.Content = map;
    }

    The MapSource.FromUri method requires a Uri argument, and returns a new MapSource object that reads the shape source from the Uri. There’s also an implicit conversion for string-based URIs.

    <map:SfMaps>
        <map:SfMaps.Layer>
            <map:MapShapeLayer ShapesSource="https://cdn.syncfusion.com/maps/map-data/world-map.json" />
        </map:SfMaps.Layer>
    </map:SfMaps>
    public MainPage()
    {
        InitializeComponent();
        SfMaps map = new SfMaps();
        MapShapeLayer layer = new MapShapeLayer();
        layer.ShapesSource = MapSource.FromUri(new Uri("https://cdn.syncfusion.com/maps/map-data/world-map.json"));
        map.Layer = layer;
        this.Content = map;
    }

    Load an embedded file

    • Embedded sources are loaded based on their resource ID, which is compromised of the name of the project and its location in the project.
    • You can load both json data and shapefile.
    • For example, placing australia.json in the root folder of a project named MyProject will result in a resource ID of MyProject.australia.json. Similarly, placing world1.shp in the Assets folder of a project named MyProject will result in a resource ID of MyProject.Assets.world1.shp
    • Right-click the added shapefile, and navigate to properties.
    • Choose the EmbeddedResource option under BuildAction of respective shapefile.

    NOTE

    You can get the australia.json file here.

    public MainPage()
    {
        InitializeComponent();
        SfMaps map = new SfMaps();
        MapShapeLayer layer = new MapShapeLayer();
        layer.ShapesSource = MapSource.FromResource("MyProject.australia.json");
        map.Layer = layer;
        this.Content = map;
    }

    Loading from stream

    SfMaps provides support to load the json data or shapefile as bytes from stream.

    public MainPage()
    {
        InitializeComponent();
        SfMaps map = new SfMaps();
        MapShapeLayer layer = new MapShapeLayer();
        Assembly assembly = Application.Current?.GetType().GetTypeInfo().Assembly;
        var jsonStream = assembly?.GetManifestResourceStream("MyProject.Assets.australia.json");
        layer.ShapesSource = MapSource.FromStream(jsonStream);
        map.Layer = layer;
        this.Content = map;
    }

    maps basic view

    Mapping the data source for shape layer

    The DataSource property accepts the collection values as input. The PrimaryValuePath property refers to the data ID in DataSource.

    The ShapeDataField property is similar to the PrimaryValuePath property. It refers to the column name in the data property of shape layers to identify the shape. When the values of the PrimaryValuePath property in the DataSource property and the values of ShapeDataField in the data property match, the associated object from the dataSource will be bound to the corresponding shape.

    <map:SfMaps>
        <map:SfMaps.Layer>
            <map:MapShapeLayer x:Name="layer"
                               ShapeDataField="STATE_NAME"
                               DataSource="{Binding Data}"        
                               PrimaryValuePath="State"  />
        </map:SfMaps.Layer>
    </map:SfMaps>
    public MainPage()
    {
    	InitializeComponent();
    	this.layer.ShapesSource = MapSource.FromResource("MyProject.australia.json");
    }
    
    public class ViewModel
    {
        public ObservableCollection<Model> Data { get; set; }
        public ViewModel()
        {
            Data = new ObservableCollection<Model>();
            Data.Add(new Model("New South Wales", "New\nSouth Wales", 1));
            Data.Add(new Model("Queensland", "Queensland",2));
            Data.Add(new Model("Northern Territory", "Northern\nTerritory",3));
            Data.Add(new Model("Victoria", "Victoria",4));
            Data.Add(new Model("Tasmania", "Tasmania",5));
            Data.Add(new Model("Western Australia", "Western Australia",6));
            Data.Add(new Model("South Australia", "South Australia",7));
        }
    
        public class Model
        {
            public string State { get; set; }
            public string StateCode { get; set; }
            public int ID { get; set; }
            public Model(string state, string stateCode, int id)
            {
                State = state;
                StateCode = stateCode;
                ID = id;
            }
        }
    }

    NOTE

    Add shape layer maps elements

    Add the basic maps elements such as data labels, legend, and tooltip as shown in the below code snippet.

    • Data labels - You can show data labels using the ShowDataLabels property and also, customize it using the DataLabelSettings property.

    • Markers - You can show markers at any position on the map by providing latitude and longitude position to the MapMarker, which is from the Markers collection.

    • Legend - You can enable legend using the Legend property. The legend’s text is displayed based on the ColorMapping.Text property. It is possible to customize the legend text using the TextStyle property.

    • Tooltip - You can enable tooltip for the shapes using the ShowShapeTooltip property. It will be displayed when you interacts with the shapes i.e., while tapping in touch devices and hover in the mouse enabled devices.

    <Grid>
        <Grid.BindingContext>
            <local:ViewModel />
        </Grid.BindingContext>
    
        <map:SfMaps>
            <map:SfMaps.Layer>
                <map:MapShapeLayer x:Name="layer"
                                   ShapeDataField="STATE_NAME"
                                   DataSource="{Binding Data}"
                                   PrimaryValuePath="State" 
                                   ShowDataLabels="True"
                                   ShowShapeTooltip="True"
                                   ShapeColorValuePath="ID">
    
                    <!--Set Data Label-->
                    <map:MapShapeLayer.DataLabelSettings>
                        <map:MapDataLabelSettings DataLabelPath="StateCode" />
                    </map:MapShapeLayer.DataLabelSettings>
                    
                    <!--Set Color mapping-->
                    <map:MapShapeLayer.ColorMappings>
                        <map:EqualColorMapping Color="#d0b800"
                                               Value="1"
                                               Text="NSW" />
                        <map:EqualColorMapping Color="#00d5cf"
                                               Value="2"
                                               Text="Queensland" />
                        <map:EqualColorMapping Color="#cf4eee"
                                               Value="3"
                                               Text="Victoria" />
                        <map:EqualColorMapping Color="#4f93d8"
                                               Value="4"
                                               Text="Tasmania" />
                        <map:EqualColorMapping Color="#8b6adf"
                                               Value="5"
                                               Text="WA" />
                        <map:EqualColorMapping Color="#7bff67"
                                               Value="6"
                                               Text="SA" />
                        <map:EqualColorMapping Color="#ff4e42"
                                               Value="7"
                                               Text="NT" />
                    </map:MapShapeLayer.ColorMappings>
    
                    <!--Set Markers-->
                    <map:MapShapeLayer.Markers>
                        <map:MapMarkerCollection>
                            <map:MapMarker x:Name="Adelaide"
                                           Latitude="-34.928497"
                                           Longitude="138.600739" />
                        </map:MapMarkerCollection>
                    </map:MapShapeLayer.Markers>
                    
                    <!--Set Legend-->
                    <map:MapShapeLayer.Legend>
                        <map:MapLegend SourceType="Shape"
                                       Placement="Bottom" />
                    </map:MapShapeLayer.Legend>
                </map:MapShapeLayer>
            </map:SfMaps.Layer>
        </map:SfMaps>
    </Grid>
    public MainPage()
    {
        InitializeComponent();
    	ViewModel viewModel = new ViewModel();
        this.BindingContext = viewModel;
        SfMaps maps = new SfMaps();
        MapShapeLayer layer = new MapShapeLayer();
        layer.ShapesSource = MapSource.FromResource("MyProject.australia.json");
        layer.DataSource = viewModel.Data;
        layer.PrimaryValuePath = "State";
        layer.ShapeDataField = "STATE_NAME";
        layer.ShapeColorValuePath = "ID";
        layer.ShowDataLabels = true;
        layer.ShowShapeTooltip = true;
    
        layer.DataLabelSettings = new MapDataLabelSettings()
        {
            DataLabelPath = "StateCode"
        };
    
        layer.ColorMappings = new ObservableCollection<ColorMapping>()
        {
            new EqualColorMapping
    		   {
    		      Color = Color.FromRgb(208,183,0),
    			  Value = "1",
                  Text="NSW"
    		   },
            new EqualColorMapping
    		   { 
    		      Color = Color.FromRgb(0,213,207),
    		      Value = "2" ,
    			  Text="Queensland"
    		   },
            new EqualColorMapping
    		   {
    		      Color = Color.FromRgb(207,78,238),
    			  Value = "3",
                  Text="Victoria"
    		   },
            new EqualColorMapping
    		   {
    		      Color = Color.FromRgb(79,147,216),
    			  Value = "4",
    			  Text="Tasmania"
    		   },
            new EqualColorMapping
    		   {
    		      Color = Color.FromRgb(139,106,223),
    			  Value = "5",
    			  Text="WA"
    		   },
            new EqualColorMapping
    		   {
    		      Color = Color.FromRgb(123,255,103),
    			  Value = "6",
    			  Text="SA"
    		   },
            new EqualColorMapping
    		   {
    		      Color = Color.FromRgb(255,78,66),
    			  Value = "7",
    			  Text="NT"
    		   },
        };
    
        MapMarker mapMarker = new MapMarker();
        mapMarker.Latitude = -34.928497;
        mapMarker.Longitude = 138.600739;
        MapMarkerCollection mapMarkers =new MapMarkerCollection
        {
           mapMarker
        };
        layer.Markers = mapMarkers;
    
        MapLegend legendSet = new MapLegend();
        legendSet.SourceType = LegendSourceType.Shape;
        legendSet.Placement = LegendPlacement.Bottom;
        layer.Legend = legendSet;
    
        maps.Layer = layer;
        this.Content = maps;
    }
    
    public class ViewModel
    {
        public ObservableCollection<Model> Data { get; set; }
        public ViewModel()
        {
            Data = new ObservableCollection<Model>();
            Data.Add(new Model("New South Wales", "New\nSouth Wales", 1));
            Data.Add(new Model("Queensland", "Queensland",2));
            Data.Add(new Model("Northern Territory", "Northern\nTerritory",3));
            Data.Add(new Model("Victoria", "Victoria",4));
            Data.Add(new Model("Tasmania", "Tasmania",5));
            Data.Add(new Model("Western Australia", "Western Australia",6));
            Data.Add(new Model("South Australia", "South Australia",7));
        }
        
        public class Model
        {
            public string State { get; set; }
            public string StateCode { get; set; }
            public int ID { get; set; }
            public Model(string state, string stateCode, int id)
            {
                State = state;
                StateCode = stateCode;
                ID = id;
            }
        }
    }

    Maps getting started

    NOTE

    • Get the complete getting started sample from GitHub link.
    • You can refer to our .NET MAUI Maps feature tour page for its groundbreaking feature representations.