Blazor WebAssembly: Loading and Drawing Data¶
Namespace: ThinkGeo.UI.Blazor
Applies to: ThinkGeo Web Maps, Blazor WebAssembly on .NET 8 or later
Tested with: ThinkGeo.UI.Blazor 15.1.0, .NET 10, a standalone Blazor WebAssembly app, Chrome
Overview¶
In Blazor WebAssembly your C# code runs in the visitor's browser. MapView and its overlays work the same as on the server; what changes is where the data comes from, what the browser can see, and which kind of drawing needs extra setup. This guide builds a standalone WebAssembly map that shows its basemap at once, then loads its data with a loading message and an error message. The Web Maps Quick Start has the shortest version of the same app.
What changes from the server¶
| Interactive Server | WebAssembly | |
|---|---|---|
Your C# code and FeatureSources run | on the server | in the browser |
| Files the code can open | the server's | only what the app downloaded into its own in-memory file system |
| Vector tiles are cut | on the server, sent over the circuit | in the browser, by the same code |
| Secrets in the code, such as a Cloud key or a connection string | stay on the server | are downloaded with the app, and anyone can read them |
Classic LayerOverlay drawing | SkiaSharp on the server | SkiaSharp's WebAssembly build, which the project must add |
| A database server | is reached from the server | cannot be reached from the browser; serve the data through an API of yours instead |
Set up the project¶
-
Create a Blazor WebAssembly Standalone App (C#, .NET 10) and add the ThinkGeo.UI.Blazor package:
dotnet new blazorwasm -n BlazorWasmSample cd BlazorWasmSample dotnet add package ThinkGeo.UI.Blazor -
Add the namespaces to
_Imports.razor:@using ThinkGeo.Core @using ThinkGeo.UI.Blazor -
Unpack WorldCapitals.zip into
wwwroot/Data, with the five files directly in it. Everything inwwwrootis published with the app and can be downloaded from it.
The build prints WASM0001 warnings about SQLite functions. They concern SQLite-based data sources and do not affect this guide.
Keep <script type="importmap"></script> in wwwroot/index.html and <OverrideHtmlAssetPlaceholders>true</OverrideHtmlAssetPlaceholders> in the project file, as the .NET 10 template has them. A project that turns the setting on without the tag, for example one made from an older template, does not start once it is published to a plain web server, because the browser cannot find the fingerprinted dotnet.js.
Download the data into the browser¶
A ShapeFileFeatureSource opens a file by its path. In WebAssembly, paths lead to an in-memory file system that starts empty, so the app downloads the files with HttpClient and writes them there first. All the files of the shapefile are needed, not only .shp.
The page below shows the basemap at once, while the data is downloading. The VectorTileOverlay is only declared once its sources exist, inside @if, so it never opens a file that is not there yet. A failed download leaves the basemap on the map and says what went wrong.
@page "/"
@inject HttpClient Http
<p>@status</p>
<MapView 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~" />
@if (capitals != null)
{
<VectorTileOverlay Id="capitals" FeatureSources="@capitals" StyleJson="@capitalsJson" />
}
</OverlaysSetting>
</MapView>
@code {
private GeoCollection<FeatureSource>? capitals;
private string status = "Loading the capitals…";
protected override async Task OnInitializedAsync()
{
try
{
// Download the shapefile and write it where the WebAssembly app can open it.
var folder = Path.Combine(Path.GetTempPath(), "Data");
Directory.CreateDirectory(folder);
foreach (var extension in new[] { "shp", "shx", "dbf", "idx", "ids" })
{
var bytes = await Http.GetByteArrayAsync($"Data/WorldCapitals.{extension}");
await File.WriteAllBytesAsync(Path.Combine(folder, "WorldCapitals." + extension), bytes);
}
capitals = new GeoCollection<FeatureSource>
{
{ "WorldCapitals", new ShapeFileFeatureSource(Path.Combine(folder, "WorldCapitals.shp"))
{
ProjectionConverter = new ProjectionConverter(4326, 3857)
}
}
};
status = "The capitals are on the map.";
}
catch (HttpRequestException e)
{
// The basemap is already on the map; say what is missing instead of leaving it blank.
status = $"The capitals could not be loaded (HTTP {(int?)e.StatusCode}).";
}
}
private const string capitalsJson = """
{
"layers": [
{ "type": "circle", "source-layer": "WorldCapitals",
"paint": { "circle-radius": 4, "circle-color": "#FFFFFF",
"circle-stroke-color": "#000000", "circle-stroke-width": 2 } }
]
}
""";
}
OnInitializedAsync lets the page render while it awaits, so the map and the loading message are on the page before the first file arrives. When the method returns, the page renders again, the @if turns true, and the overlay is added to the map that is already there.
Exception messages are shortened in WebAssembly builds, so the page shows the HTTP status code rather than e.Message.
Large data¶
The files are downloaded whole, every time the app starts, and held in the browser's memory. That suits files of a few megabytes. For larger data:
- Serve vector tiles from a WebAPI service, as the Web Maps Quick Start builds one, and name its tile address as a source in the style document: the browser then fetches only the tiles it shows.
- Or serve only the features the page needs, through an API of yours, and put them in an
InMemoryFeatureSource.
Keys and secrets¶
Everything in a WebAssembly app is downloaded to the visitor's browser, the code included. A ThinkGeo Cloud key in a page can be read by anyone who opens it. Use a JavaScript client key, restricted to your site's domain at cloud.thinkgeo.com; Client Keys explains the restriction. Keep credentials for anything else, such as a database, on a server and call it through an API.
The testing key in these guides is ThinkGeo's public one; replace it with your own before you publish.
Classic drawing in WebAssembly¶
A VectorTileOverlay with a style document needs nothing more in WebAssembly: the browser draws its tiles. Anything SkiaSharp draws where the .NET code runs needs SkiaSharp's WebAssembly build in the project: a LayerOverlay's image tiles, and the icons a MapStyle draws from classic styles, such as style.Images.Add("star", new PointStyle(...)). Without it, the page fails with DllNotFoundException: libSkiaSharp. The Blazor WebAssembly sample, Query and Print in the Browser, shows the project settings: it queries shapefiles and prints a vector PDF in the browser.
Interactive WebAssembly and Auto in a Blazor Web App¶
A Blazor Web App can run single pages in the browser with @rendermode InteractiveWebAssembly. Those pages live in the app's .Client project and download their data as above. With @rendermode InteractiveAuto a page runs on the server for a first visit and in the browser for later ones, so its data loading has to work in both places, for example by reading the data through an API that both can call. The examples in these guides have not been tested in these two modes.