Skip to content

Overlays and RedrawAsync (Blazor)

Namespace: ThinkGeo.UI.Blazor
Applies to: ThinkGeo Web Maps, Blazor on .NET 8 or later
Tested with: ThinkGeo.UI.Blazor 15.1.0, .NET 10, Chrome


Overview

Everything a MapView shows comes from its overlays. This guide covers how overlays are declared and referenced, the two ways a change reaches the map (a new parameter value, or RedrawAsync), and how overlays are cleaned up.

It assumes a map set up as in MapView and Render Modes.


Declaring overlays

Overlays are declared inside the map's OverlaysSetting, and drawn in that order, the first at the bottom:

<MapView @ref="map" Id="map" MapUnit="GeographyUnit.Meter"
         Center="@(new PointShape(0, 2000000))" Zoom="2" Width="900" Height="600">
    <OverlaysSetting>
        <ThinkGeoCloudVectorMapsOverlay Id="basemap" MapType="ThinkGeoCloudVectorMapsMapType.Light"
                                        ApiKey="SGjwpxF60knqZi3R0A9RRE3GqiuRA1LsnxHMot7rJ58~" />
        <LayerOverlay @ref="classicOverlay" Id="classic" Layers="@classicLayers" />
        <VectorTileOverlay @ref="vectorOverlay" Id="vector" FeatureSources="@vectorSources"
                           StyleJson="@vectorJson" IsVisible="@showVector" />
    </OverlaysSetting>
</MapView>
Overlay What it draws Where it is drawn
ThinkGeoCloudVectorMapsOverlay A ThinkGeo Cloud vector basemap. In the browser.
ThinkGeoCloudRasterMapsOverlay, WmsTileOverlay, WmtsTileOverlay Image tiles from ThinkGeo Cloud, a WMS or a WMTS service. Fetched by the browser.
VectorTileOverlay Your FeatureSources, styled by a style document. In the browser, from vector tiles your code cuts.
LayerOverlay Classic layers: FeatureLayers with styles set in code. Into image tiles, by SkiaSharp, where your code runs.

Give each overlay an Id. It must be unique on the map, and is how the browser tells the overlays apart. @ref gives your code the overlay component, the same way it gives it the map; the field is set when the page first renders.

Markers and popups are not declared in OverlaysSetting but in MarkerOverlaySetting and PopupOverlaySetting: Events, Markers and Popups.


Two kinds of change

A change reaches the map in one of two ways, and which one depends on whether Blazor can see it.

A new parameter value. When a value written in the overlay's tag changes, such as IsVisible="@showVector" or StyleJson="@vectorJson", Blazor passes the new value to the overlay when the page renders again, and the overlay applies it. There is nothing more to call. Changing a field in an event handler re-renders the page by itself.

A change inside an object the overlay already holds. Adding a feature to an InMemoryFeatureSource, changing a style object, or editing the rows a FeatureSource reads changes no parameter: the overlay holds the same object as before and cannot tell. Call the overlay's RedrawAsync to have it draw again.

You changed The map follows by
IsVisible, StyleJson, Style assigned a new document, FeatureSources assigned a new collection itself, on the next render
Features added to, removed from or moved in a source await overlay.RedrawAsync()
A MapStyle object changed in place await overlay.RedrawAsync()
The data behind a LayerOverlay's layers, or their styles await overlay.RedrawAsync()

What RedrawAsync costs depends on the overlay. A VectorTileOverlay over a small in-memory source hands its features to the browser whole, and a redraw hands them over again, without a tile being fetched. Over a file or a database, it has the browser ask for its tiles again, which the server cuts anew. A LayerOverlay has every tile drawn again on the server. Redraw the overlay that changed, not all of them, and redraw once after a batch of changes rather than once per feature.

Example: add points to a vector and a classic overlay

@page "/overlays"
@rendermode InteractiveServer

<button @onclick="AddPointAsync">Add a point</button>
<label><input type="checkbox" @bind="showVector" /> Show the vector points</label>
<span>@count points</span>

<MapView @ref="map" Id="map" MapUnit="GeographyUnit.Meter"
         Center="@(new PointShape(0, 2000000))" Zoom="2" Width="900" Height="600">
    <OverlaysSetting>
        <ThinkGeoCloudVectorMapsOverlay Id="basemap" MapType="ThinkGeoCloudVectorMapsMapType.Light"
                                        ApiKey="SGjwpxF60knqZi3R0A9RRE3GqiuRA1LsnxHMot7rJ58~" />
        <LayerOverlay @ref="classicOverlay" Id="classic" Layers="@classicLayers" />
        <VectorTileOverlay @ref="vectorOverlay" Id="vector" FeatureSources="@vectorSources"
                           StyleJson="@vectorJson" IsVisible="@showVector" />
    </OverlaysSetting>
</MapView>

@code {
    private MapView map = default!;
    private LayerOverlay classicOverlay = default!;
    private VectorTileOverlay vectorOverlay = default!;
    private bool showVector = true;
    private int count;
    private readonly Random random = new();

    // Vector: the points are drawn in the browser, from the style document below.
    private readonly InMemoryFeatureSource vectorPoints = new();
    private GeoCollection<FeatureSource> vectorSources = default!;

    // Classic: the points are drawn into raster tiles on the server.
    private readonly InMemoryFeatureLayer classicPoints = new();
    private GeoCollection<LayerBase> classicLayers = default!;

    private const string vectorJson = @"{
  ""layers"": [
    { ""type"": ""circle"", ""source-layer"": ""points"",
      ""paint"": { ""circle-radius"": 6, ""circle-color"": ""#3060C8"",
                   ""circle-stroke-color"": ""#FFFFFF"", ""circle-stroke-width"": 2 } }
  ]
}";

    protected override void OnInitialized()
    {
        vectorSources = new GeoCollection<FeatureSource> { { "points", vectorPoints } };

        classicPoints.ZoomLevelSet.ZoomLevel01.DefaultPointStyle = PointStyle.CreateSimpleCircleStyle(GeoColors.Red, 12, GeoColors.White, 2);
        classicPoints.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
        classicLayers = new GeoCollection<LayerBase> { classicPoints };
    }

    private async Task AddPointAsync()
    {
        // A point somewhere between 60°S and 60°N, in the map's Web Mercator meters.
        var x = random.Next(-18000000, 18000000);
        var y = random.Next(-8000000, 8000000);

        // Adding to a collection changes no parameter, so neither overlay can see it:
        // tell each one to draw again.
        vectorPoints.InternalFeatures.Add(new Feature(x, y + 500000));
        classicPoints.InternalFeatures.Add(new Feature(x, y));
        count++;

        await map.WhenReady;
        await vectorOverlay.RedrawAsync();
        await classicOverlay.RedrawAsync();
    }
}

Each click puts a blue point, drawn in the browser, above a red one, drawn on the server. The checkbox hides the blue points through a parameter, with no RedrawAsync.

await map.WhenReady keeps the handler safe if the button is clicked before the map has loaded: RedrawAsync throws until then. In a handler that can only run on a loaded map, such as a map click, it is not needed.


Updates from outside the page

Code that is not a Blazor event handler, such as a timer, a message from a queue or a Task.Run, does not run on the page's synchronization context. Call RedrawAsync, and change the fields the page renders from, through the component's InvokeAsync, and call StateHasChanged when the page itself must render again:

private async void OnPositionReceived(object? sender, Feature vehicle)
{
    await InvokeAsync(async () =>
    {
        vehicles.InternalFeatures.Add(vehicle);
        await vehicleOverlay.RedrawAsync();
        StateHasChanged();
    });
}

Several updates a second are best collected and drawn together, for example once every 500 milliseconds, rather than redrawn one by one.


Adding overlays in code

An overlay need not be declared in markup. Overlays added to MapView.Overlays are attached to the map as they are added, and removed from it as they are removed:

map.Overlays.Add("routes", new LayerOverlay { Layers = { routeLayer } });
map.Overlays.Remove("routes");

Markup is the simpler choice when the overlays are known when the page is written. A declared overlay can also come and go with @if: an overlay that Blazor takes out of the page takes itself off the map.


Cleanup

When the user leaves the page, Blazor disposes it, and the map and its overlays release what they hold in the browser. Your code has three things to look after:

  • Layers and sources you opened yourself. An overlay closes a layer it opened, but a layer that was already open when the overlay got it is left open. Close it in the page's Dispose.
  • Timers and subscriptions. Stop them in Dispose, so they do not call RedrawAsync on a map that is gone.
  • Overlays added in code are disposed with the map. One removed from MapView.Overlays earlier is detached but not disposed, and can be added again.
@implements IDisposable

@code {
    public void Dispose()
    {
        timer?.Dispose();
    }
}

See also