Skip to content

About

Leaflet for Blazor is a library that provides components for displaying map in Blazor applications. KEYWORDS: 🟦 Pure C#, Ξ» LINQ Integration, πŸ”— Fluent API, βž– Zero JavaScript Config, πŸ”ŒPlugins Framework

Topics

Resources

Stars

150 stars

Watchers

6 watching

Forks

Latest commit

Β 

History

1,678 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

LeafletForBlazor Leaflet Map for Blazor

Leaflet for Blazor is a library that provides components for displaying maps in Blazor applications.

πŸ”‘ KEYWORDS: Pure C# - Write map logic entirely in .NET / no JavaScript interop boilerplate, LINQ Integration - Destructuring/Structuring LINQ expression, Fluent API - objects Hierarchical and Linguistic structure and Chain methods, Plugins Framework - allows you to extend LeafletForBlazor, Zero JavaScript Config for standard use - no script references and no css links etc

NuGet Version NuGet DownloadsGitHub stars GitHub last commitLicense: MIT

🧩 Version 4.0 ♻️rehydrates the Map control. The new control inherits the minimalism of the Map control and the optimizations of the RealTimeMap control.

βš™οΈ Core Concepts

  1. For standard usage, no specific configurations for JavaScript or HTML are required.

  2. Optimized code through various solutions

    • Minimizing the number of calls to JavaScript;
    • Minimizing JS Interop payload size through destructuring and structuring LINQ expressions for the invokes C# -> JavaScript;
    • Reducing size of the JavaScript code by removing unused code.
    • Memory Cache
    • Fluent API, a design pattern that allows code to be written in a readable way, similar to an English sentence
  3. Plugins framework - By writing simple wrapper code, the MapPlugins framework allows LeafletForBlazor to be extended with already developed Leaflet.js plugins (add-ons) - more about Leaflet.js Plugins.

More about Core Concept

πŸš€ Quick Start

πŸ”§ 1. Project setup

πŸ”΅ Add the Map component to your project in just 3 steps:

  1. Install the NuGet package:
  • From VS interface: Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution...

    Search for "LeafletForBlazor" and add the package to the project or solution.

  • From Package Manager Console: Tools -> NuGet Package Manager -> Package Manager Console

      NuGet\Install-Package LeafletForBlazor
  • From PowerShell:
     dotnet add package LeafletForBlazor
  1. Add the required namespaces in _Imports.razor

To do this, add the following directives to the _Imports.razor file

        @using LeafletForBlazor                             //working with package classes
        @using static LeafletForBlazor.Map                  //working with Map class
        @using static LeafletForBlazor.techs.maps.Leaflet   //working with Leaflet API
  1. Use the Map component

Razor

        <Map height="100vh" width="100vw"/>

πŸ—ΊοΈ 2. Default Map configuration

Use the loadParameters property to set the initial map view:

Razor

        <Map loadParameters="@loadParameters" height="100vh" width="100vw"/>

C# - Default Map Configuration

    LoadParameters loadParameters = new()
    {
        location = new Location()                                               //Default center of the Map View
        {
            latitude = 50.83112274500208,
            longitude = 4.407353347319803
        },
        zoomLevel = 10                                                          //Default zoom level
    };

Additional default configurations are available, including attribution control visibility, map basemap layers, and map controls such as the scale control.

more about Map Configuration - Blazor WebAssembly Standalone App

more about Map Configuration - .NET MAUI Blazor Hybrid App

🌣 Map post-load logic

After initializing the Leaflet map instance on the client side, you can modify map settings and load spatial data. The OnAfterMapLoaded event of the Map component can be used for operations that require an initialized mapβ€”for example, accessing the map's initial state, adding geometries, or loading data from files.

Razor

    <Map height="100vh" width="100vw" OnAfterMapLoaded="@OnAfterMapLoaded" />

C# - Handler signature

The event method returns a set of parameters useful for configuring the initial state of the map: Map, centerOfView and other.

    private Task OnAfterMapLoaded(MapEventArgs args)
    {
        var map = args.sender as Map;  //allows access to the Map object
        
        Console.WriteLine($"Map loaded. Dimensions are - Height: {map!.height}, Map Width: {map!.width}");
        Console.WriteLine($"lat: {args.centerOfView.latitude} long: {args.centerOfView.longitude}");
        
        return Task.CompletedTask;
    }

It is important to note that args.sender represents the Map class (the map functionality).

more about Map Events - Blazor WebAssembly Standalone App

more about Map Events - .NET MAUI Blazor Hybrid App

🌍 3. Map Interaction & UI

πŸ‘οΈ View class

View is the class that allows you to control the visible area of ​​the map.

For example, you can use the View class to get the map's center:

Razor

 <Map height="100vh" width="100vw" OnAfterMapLoaded="@OnAfterMapLoaded" />

C#

    private async Task OnAfterMapLoaded(MapEventArgs args)
    {
        var map = args.sender as Map;
        var center = await map!.View.getCenterAsync();
    }

...setting the map center - C#:

    private async Task OnAfterMapLoaded(MapEventArgs args)
    {
        var map = args.sender as Map;
        map!.View.SetCenter(40.24, 5.48);
    }

more about View class

ℹ️ Attribution class

The Attribution class provides the methods needed to interact with the map's attributionControl:

attribtion control

For example, you can completely remove the attributionControl:

Razor

 <Map height="100vh" width="100vw" OnAfterMapLoaded="@OnAfterMapLoaded" />

C#

private async Task OnAfterMapLoaded(MapEventArgs args)
{
    var map = args.sender as Map;
    await map.Attribution.SetPrefix("<img style='height: 14px;weight:14px;' src = 'http://localhost:5234/icons/leaflet.png'>LeafletForBlazor</img>");
}

more about Attribution class

πŸ“ 4. Working with data

πŸ“ Geometric class

The Geometric class contains classes that operate on geometries obtained from various sources.

πŸ“ StreamPoint collection

StreamPoint collection provides real-time map synchronization - any property change (coordinates, appearance, timestamp) instantly updates the map visualization. Objects are cached for performance but remain fully dynamic.

The StreamPoint collection is hosted by map.Geometric.Points and provides you methods for handling predefined but hierarchically extensible root data structure:

  1. Add(), Remove(), Update() for collection handling;
  2. Appearance() for point the aspect in the map;
  3. StreamPoint collection events;

Razor

 <Map height="100vh" width="100vw" OnAfterMapLoaded="@OnAfterMapLoaded" />

C# - Example of adding a StreamPoint to the collection

    private async Task OnAfterMapLoaded(MapEventArgs args)
    {
        var map = args.sender as Map;
        var streamPoints = new List<StreamPoint>()
        {
                new StreamPoint()
                {
                    coordinates = new Coordinates()
                    {
                        xy = new double[2] { 50.86,  4.22 }
                    },
                    guid = new Guid("00000000-0000-0000-0000-000000000001"),
                    type = "Industrial"
                }
        }
        await map!.Geometric.Points.Add(streamPoint);
    }

more about StreamCollection - Blazor WebAssembly Standalone App

more about StreamCollection - .NET MAUI Blazor Hybrid App

πŸ“ Working with Files

The map.Geometric.From.Files class allows you to load data from files stored on a web service host (https://...). Full RFC 7946 Feature Support. In addition, extended RFC 7946 data formats allow for the assignment of different styles (Appearance) to spatial elements displayed on the map.

Razor

 <Map height="100vh" width="100vw" OnAfterMapLoaded="@OnAfterMapLoaded" />

C# - Example of fetching data from Files

    private async Task OnAfterMapLoaded(MapEventArgs args)
   {
       var map = args.sender as Map;
       var path = "https://MyServer";
      
       await map!.Geometric.From.Files!.FetchAsync(
                                                   new List<string> { $"{path}/data/infrastructure.json"}, 
                                                   PoolingDelay.Short
                                                   );
   }

more about working with files

πŸ“¦ Working with Objects

The map.Geometric.From.Objects class allows you to load data from objects. Full RFC 7946 Feature Support.

Razor

 <Map height="100vh" width="100vw" OnAfterMapLoaded="@OnAfterMapLoaded" />

C# - Example of loading data from Objects

    private async Task OnAfterMapLoaded(MapEventArgs args)
   {
       int primaryKey = 0; 
       var objects = new List<object>
       {
           new Feature()           //RFC 7946 class structure
       };
       await map!.Geometric.From.Objects!.LoadAsync(objects).WithKey(primaryKey);
   }

more about working with Objects

Working with Template Literals

The content parameter of the Tooltip element (Files and Objects JSON "appearance") allows the use of Template Literals. The Template Literal definition, written in C# and passed via Invoke to the Leaflet.js functions, uses " instead of `.

more about Tooltips and Template Literals

πŸ“Š Dashboard

StreamPoint collection can be used to monitor moving targets: vehicles, boats, aircraft, even fleets of vehicles, drones and so one. Both the map and the StreamPoint collection can be configured to create a Map Dashboard.

SigmaDrone

more about Map Dashboard

πŸ”Œ Map plugins

However, extending the NuGet package can only be implemented by adding JavaScript code.

The Map component provides the MapPlugins slot (Plugin Framework), allowing you to extend LeafletForBlazor with additional Leaflet functionality. It enables the development of features in JavaScript and grants you access to the map (the Leaflet map instance) and the L object.

        <Map>
            <MapPlugins>
                        @* Custom Blazor Component - Leaflet.js Fullscreen plugin  *@
                        <Fullscreen            
                            Map="@context.map" 
                            L="context.LeafletCore"
                            url="https://unpkg.com/leaflet.fullscreen/dist/Control.FullScreen.umd.js"
                            href="https://unpkg.com/leaflet.fullscreen/dist/Control.FullScreen.css" />
						@*   other plugins or custom functionality  *@
            </MapPlugins>
        </Map>
        //This is an example of usage. You can find the complete implementation at the link below.

By writing simple wrapper code, the MapPlugins framework allows LeafletForBlazor to be extended with already developed Leaflet.js add-ons.

more about MapPlugins and WASM

more about MapPlugins and MAUI

πŸ“¦ Map Components

The Map component provides the MapComponents slot, allowing you to extend the LeafletForBlazor map with graphical interface elements.

        <Map>
            <MapComponents>
                <Toolbar/>
				@*   other MapComponents or html elements  *@
            </MapComponents>
        </Map>
        //This is an example of usage. You can find the complete implementation via the links in the table below.
Description Image
The component displays a Legend on the map, allowing users to quickly understand the meaning of the symbols and colors applied to data layers. In the current version, the legend is only available for GeoJSON files and StreamPoint Collection. Legend can also be used in .NET MAUI projects. Legend
Contextual display driven by data source with MapPopup. GeoJSON File and MapPopup Component MapPopup
The Toolbar it is a map component that allows for expansion with various buttons and even tools. Toolbar
A Toggle is a check/uncheck component that can be hosted in a toolbar. Toggle

πŸ“ˆ Performance

In the repo, you will find a VS Project(s) that you can use to check the performance of the NuGet package.


O-L I - αΆœβ΄Λ‘α΅˜β·α΅˜β΅α΅˜αΆ Λ‘α΅‰β·βΈα΅˜βΏ πŸ• c3z4r

Thank you for choosing this package!

Laurentiu Ichim

About

Leaflet for Blazor is a library that provides components for displaying map in Blazor applications. KEYWORDS: 🟦 Pure C#, Ξ» LINQ Integration, πŸ”— Fluent API, βž– Zero JavaScript Config, πŸ”ŒPlugins Framework

Topics

Resources

Stars

150 stars

Watchers

6 watching

Forks

Releases

Packages

Used by

Contributors

Languages