How to use Azure Maps in Blazor

How to use Azure Maps in Blazor

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:

  • Visual Studio 2022 or later with the ASP.NET and web development workload
  • .NET 7.0 SDK or later
  • An active Azure subscription with an Azure Maps account
  • Azure Maps SDK key

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.

  1. Go to the Azure Portal and sign in.
  2. Click on "Create a resource" and search for "Azure Maps."
  3. Select "Azure Maps" and click on "Create."
  4. Fill in the required details and click "Review + Create."
  5. Once the deployment is complete, go to the resource and copy the primary key for later use.

To create a new Blazor WebAssembly project use the following steps.

  1. Launch Visual Studio and select "Create a new project."
  2. Choose "Blazor WebAssembly App" from the list of templates and click "Next."
  3. Enter a project name, location, and solution name, then click "Create."
  4. In the "Configure your new project" window, select ".NET 7" and enable the "ASP.NET Core hosted" checkbox. Click "Create."


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.


Resources

要查看或添加评论,请登录

Serhii Kokhan的更多文章

  • AsyncLocal vs ThreadLocal

    AsyncLocal vs ThreadLocal

    ??Introduction Let’s be honest - working with async programming and multithreading in .NET can be a headache.

  • Enhancing .NET Logging with Serilog Custom Enrichers

    Enhancing .NET Logging with Serilog Custom Enrichers

    What Are Enrichers in Serilog? Enrichers in Serilog are components that automatically add extra context to log events…

    2 条评论
  • Data Synchronization in Chrome Extensions

    Data Synchronization in Chrome Extensions

    Introduction Data synchronization in Chrome extensions is a common challenge, especially for various tools ranging from…

  • Dalux Build API Changelog

    Dalux Build API Changelog

    Dalux unfortunately does not provide an official changelog for their API updates. To help developers stay informed, I…

    2 条评论
  • JSONB in PostgreSQL with EF Core - Part 2

    JSONB in PostgreSQL with EF Core - Part 2

    Introduction Welcome back to the second part of our series on using JSONB in PostgreSQL with EF Core. In our previous…

  • Proxy vs Reverse Proxy in the .NET 8 Universe

    Proxy vs Reverse Proxy in the .NET 8 Universe

    Today, we're diving into the world of proxies – but not just any proxies. We're talking about the classic proxy and its…

  • JSONB in PostgreSQL with EF Core

    JSONB in PostgreSQL with EF Core

    Introduction JSONB in PostgreSQL is a big step forward for database management. It mixes the best parts of NoSQL and…

    8 条评论
  • Mastering the use of System.Text.Json

    Mastering the use of System.Text.Json

    Introduction Handling JSON data is a daily task for many developers, given its widespread use in modern applications…

  • Firebase Multitenancy & .NET 7

    Firebase Multitenancy & .NET 7

    Introduction Firebase is a leading platform for developing mobile and web applications, offering a variety of tools and…

  • Azure SQL Database Scaling

    Azure SQL Database Scaling

    Introduction In today's fast-paced digital world, enterprises must be agile and scalable to remain competitive. For…

社区洞察

其他会员也浏览了