How to use Azure Maps in Blazor
Serhii Kokhan
Microsoft MVP??CTO & .NET/Azure Architect??Stripe Certified Professional Developer??Offering MVP Development, Legacy Migration, & Product Engineering??Expert in scalable solutions, high-load systems, and API integrations
Introduction
Blazor, a powerful and versatile framework for building web applications, allows developers to utilize C# and .NET to create full-stack web solutions. As the world increasingly relies on location-based services, integrating mapping solutions like Azure Maps into Blazor applications is an essential skill for modern web developers. In this article, we'll explore how to use Azure Maps in a Blazor application, complete with detailed explanations and code examples.
Setting up Azure Maps and Blazor
Before diving into the Azure Maps integration, ensure we have the following tools and resources:
An Azure Maps SDK key is an API key that allows us to access and authenticate with Azure Maps services. It's required when using Azure Maps in our applications, as it associates our requests with our Azure account and subscription. To obtain an Azure Maps SDK key, we must create an Azure Maps account in the Azure portal.
To create a new Blazor WebAssembly project use the following steps.
Displaying a Basic Map
Step 1: Add the Azure Maps SDK
To use Azure Maps, we will need to add the SDK to our Blazor project. In the "Client" project, add the following lines to our "wwwroot/index.html" file.
<!-- Add Azure Maps SDK CSS -->
<link rel="stylesheet" type="text/css">
<!-- Add Azure Maps SDK JavaScript -->
<script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.js"></script>
Step 2: Create a MapComponent
Now, let's create a Blazor component to display the map. In the "Client" project, create a new folder named "Components," then create a new Razor component named "MapComponent.razor" with the following content.
@inject IJSRuntime JSRuntime
<div id="mapDiv" style="width:100%;height:400px;"></div>
@code {
? ? [Parameter] public string MapsKey { get; set; }
? ? protected override async Task OnAfterRenderAsync(bool firstRender)
? ? {
? ? ? ? if (firstRender)
? ? ? ? {
? ? ? ? ? ? await JSRuntime.InvokeVoidAsync("initializeMap", MapsKey);
? ? ? ? }
? ? }
}
Step 3: Add JavaScript for map initialization
Create a new JavaScript file named "map.js" in the "wwwroot" folder of our "Client" project and add the following code.
var map;
function initializeMap(mapsKey) {
? ? // Initialize the Azure Maps
? ? atlas.setSubscriptionKey(mapsKey);
? ? // Create the map instance
? ? map = new atlas.Map("mapDiv", {
? ? ? ? view: "Auto",
? ? ? ? center: [-122.129, 47.640],
? ? ? ? zoom: 3
? ? });
}
Don't forget to include the "map.js" file in your "wwwroot/index.html" file.
<script src="map.js"></script>
Step 4: Use MapComponent on a page
Now, we can use the MapComponent on any Blazor page. For example, on the "Index.razor" page, add the following.
领英推荐
@page "/"
<h1>Azure Maps in Blazor</h1>
<MapComponent MapsKey="@MapsKey" />
@code {
? ? private string MapsKey => "AZURE_MAPS_SDK_KEY";
}
Replace "AZURE_MAPS_SDK_KEY" with the Azure Maps SDK key we obtained earlier from the Azure portal.
Step 5: Run the application
Press F5 to run the application. We should now see an interactive Azure Maps instance on the main page of our Blazor WebAssembly application.
Adding Interactivity
To add interactivity, such as adding a marker or handling click events, we can use JavaScript Interop in Blazor WebAssembly. For example, to add a marker on a map, we can modify the JavaScript code as follows.
function addMarker(position) {
? ? const marker = new atlas.HtmlMarker(position.latitude,?position.longitude);
? ? map.markers.add(marker);
? ? return marker;
}
Then, create a corresponding C# method to call this JavaScript function.
private async Task AddMarkerAsync(double latitude, double longitude)
{
? ? await JSRuntime.InvokeVoidAsync("addMarker", new { latitude, longitude });
}
To implement geolocation and display the user's location on the map, we can use the browser's Geolocation API. First, add the following JavaScript code to our wwwroot/map.js file.
function requestUserLocation() {
? ? return new Promise((resolve, reject) => {
? ? ? ? if (navigator.geolocation) {
? ? ? ? ? ? navigator.geolocation.getCurrentPosition(
? ? ? ? ? ? ? ? position => resolve({ latitude: position.coords.latitude, longitude: position.coords.longitude }),
? ? ? ? ? ? ? ? error => reject(error)
? ? ? ? ? ? );
? ? ? ? } else {
? ? ? ? ? ? reject("Geolocation is not supported by this browser.");
? ? ? ? }
? ? });
}
Next, create a C# method in our Blazor component to call this JavaScript function and add a marker to the user's location.
private async Task ShowUserLocationAsync()
{
? ? try
? ? {
? ? ? ? var userLocation = await JSRuntime.InvokeAsync<Location>("requestUserLocation");
? ? ? ? await AddMarkerAsync(userLocation.Latitude, userLocation.Longitude);
? ? }
? ? catch (Exception ex)
? ? {
? ? ? ? Console.WriteLine($"Error: {ex.Message}");
? ? }
}
public sealed class Location
{
? ? public double Latitude { get; set; }
? ? public double Longitude { get; set; }
}
Finally, add a button to our component to trigger the "ShowUserLocationAsync" method.
<button @onclick="ShowUserLocationAsync">Show My Location</button>
Summary
In this article, we have covered how to integrate Azure Maps into a Blazor WebAssembly application, including displaying a basic map, adding interactivity, and implementing geolocation. With Azure Maps and Blazor WebAssembly, we can build powerful, interactive, and modern web applications that provide rich geospatial experiences for our users.