BlazorBasics.Maps.Google 1.3.3

dotnet add package BlazorBasics.Maps.Google --version 1.3.3
                    
NuGet\Install-Package BlazorBasics.Maps.Google -Version 1.3.3
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="BlazorBasics.Maps.Google" Version="1.3.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="BlazorBasics.Maps.Google" Version="1.3.3" />
                    
Directory.Packages.props
<PackageReference Include="BlazorBasics.Maps.Google" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add BlazorBasics.Maps.Google --version 1.3.3
                    
#r "nuget: BlazorBasics.Maps.Google, 1.3.3"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package BlazorBasics.Maps.Google@1.3.3
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=BlazorBasics.Maps.Google&version=1.3.3
                    
Install as a Cake Addin
#tool nuget:?package=BlazorBasics.Maps.Google&version=1.3.3
                    
Install as a Cake Tool

Nuget Nuget

BlazorBasics.Maps.Google Library Documentation

Overview

The BlazorBasics.Maps.Google library is a Blazor component designed to integrate Google Maps functionality into Blazor applications. It provides a simple and reusable way to display a Google Map, add markers (points), manage routes and interact with the map programmatically. The library uses JavaScript interop to communicate with the Google Maps JavaScript API and supports common map operations such as adding points, showing routes, highlighting markers and get coordinates.

This library is ideal for Blazor developers who need to embed interactive maps with custom markers and routes in their web applications. It abstracts the complexity of Google Maps JavaScript API interactions while providing a clean C# interface.

Prerequisites

To use this library, you need:

  • A Google Maps API key with the Maps JavaScript API enabled. Obtain it from the Google Cloud Console.
  • A Blazor application (Server or WebAssembly).

Installation

  1. Install the NuGet Package:

    • Install the BlazorBasics.Maps.Google NuGet package in your Blazor project using the Package Manager or the .NET CLI:
      dotnet add package BlazorBasics.Maps.Google
      
  2. Add CSS Styling:

    • Ensure the map container has appropriate styling. For example, add the following CSS to your stylesheet (e.g., wwwroot/css/site.css):

      .map {
          height: 400px; /* Adjust height as needed */
          width: 100%;
      }
      
  3. Include the Component in Your Razor Page:

    • Add the GoogleMapComponent to your Razor page and provide the required parameters (ApiKey and MapId).

Usage

Basic Setup

To display a Google Map, include the GoogleMapComponent in your Razor page and provide a valid Google Maps API key and a custom Map ID. Optionally, specify an OnMapReady callback to execute code once the map is initialized.

@using BlazorBasics.Maps.Google

<GoogleMapComponent @ref="mapComponent"
                  ApiKey="TU_CLAVE_DE_API_DE_GOOGLE_MAPS"
                  MapId="TU_ID_DE_MAPA_PERSONALIZADO"
                  StartZoomLevel=15
                  OnMapReady="@OnMapReadyCallback"
                  OnClick="@OnMapClickCallback" />

@code {
    private GoogleMapComponent mapComponent = default!;

    private async Task OnMapReadyCallback()
    {
        Console.WriteLine("Map is ready!");
    }
    
    private void OnMapClickCallback(MapClickEventArgs args)
    {
        Console.WriteLine($"Lat: {args.Point?.Latitude}, Lng: {args.Point?.Longitude}");
        Console.WriteLine($"Address: {args.Address}");
    }
}

Component Parameters

Parameter Type Description
ApiKey string Required. Your Google Maps API key.
MapId string Optional. A custom map ID for styled maps. Needed to render markers and routes,
because they use advanced markers. Not needed for the center pin.
StartZoomLevel int Zoom level to apply to the view when map render. Default valur 13.
OnMapReady EventCallback A callback invoked when the map is fully loaded and ready to use.
OnClick EventCallback<MapClickEventArgs> A callback that is invoked when the map or a marker is clicked.
It returns the coordinates and address details.
ShowCenterPin bool Shows a pin fixed at the center of the map. The user moves the map under it
instead of dragging a marker. Default false.
CenterPinSvgIcon string SVG markup for the center pin. A red pin is used when it is empty.
GeocodeCenterOnMove bool Reverse geocodes the center to fill Address and Details on every move.
Set it to false to receive coordinates only and avoid geocoding calls.
Default true.
CenterChangedDebounceMilliseconds int Debounce applied before reporting the new center. Default 300.
OnCenterChanged EventCallback<MapClickEventArgs> A callback invoked after every pan or zoom with the position of the center pin.
Enabling it enables the center pin as well.

Models

The library includes two main models:

  • AddressDetails:

    • Represents full address.
    • Implement from IAddressDetails
    • Properties:
      • StreetNumber
      • Route
      • Neighborhood
      • Locality: Typically refers to the city or town name.
      • AdministrativeArea: Typically refers to the state, province, or region.
      • PostalCode
      • Country
  • PositionPoint:

    • Represents a geographic coordinate with Latitude and Longitude.
    • Implement from ILatLong and IEquatable<PositionPoint>
    • Validates coordinates to ensure they are within valid ranges (Latitude: -90 to 90, Longitude: -180 to 180).
    • Example:
      var point = new PositionPoint(latitude: 37.7749f, longitude: -122.4194f);
      
  • RoutePoint:

    • Represents a marker on the map with additional metadata.
    • Properties:
      • Id: Unique identifier for the point.
      • Position: A PositionPoint specifying the location.
      • Description: A description for the marker.
      • SvgIcon: An SVG string for a custom marker icon.
      • HtmlContent: HTML content for the marker's info window.
      • Color: Optional color for the marker. Default "black".
      • ArrowOptions: A RouteArrowOptions. Optional settings for displaying arrows on routes. Default new RouteArrowOptions().
    • Example:
      var routePoint = new RoutePoint(
          id: "point1",
          point: new PositionPoint(37.7749f, -122.4194f),
          description: "San Francisco",
          svgIcon: "<svg>...</svg>",
          htmlContent: "<h3>San Francisco</h3>",
          color: "blue",
          arrowOptions: new RouteArrowOptions()
      );
      
  • ArrowType:

    • Enumeral with Google Arrow Types.
    • Values:
      • CIRCLE
      • FORWARD_CLOSED_ARROW
      • FORWARD_OPEN_ARROW,
      • BACKWARD_CLOSED_ARROW,
      • BACKWARD_OPEN_ARROW
  • RouteArrowOptions:

    • Set parameters to show arrows with flow direction.
    • Properties:
      • Enabled: Show or not the arrows. Default false.
      • ArrowType: Enumeral ArrowType with display arrow type. Default ArrowType.FORWARD_OPEN_ARROW.
      • Scale: Arrow scale. Default 5.0
      • Color: Arrow color. Default "#1a73e8".
      • Offset: Arrow offset. Default 50.
      • RepeatPixels: Repeat the arrow every X pixels. Default 100.
  • MapClickEventArgs:

    • Event arguments for the OnClick callback. Contains information about the point where the click was made.
    • Properties:
      • MarkerId: The marker ID if one was clicked; otherwise, null.
      • Point: A ILatLong object with the click coordinates.
      • Address: A string containing the address formatted at the point of the click (reverse geocoding).
      • Details: An IAddressDetails object with the address components broken down.
  • IAddressDetails

    • Contains the broken-down components of an address obtained from reverse geocoding.
    • Properties:
      • StreetNumber
      • Route
      • Neighborhood
      • Locality: (city)
      • AdministrativeArea: (state/province)
      • Postal Code
      • Country
  • ILatLong

    • Contains latitude and longitude.
    • Properties:
      • Latitude
      • Longitude

Available Methods

The GoogleMapComponent provides the following methods to interact with the map:

  1. AddPoint(RoutePoint point):

    • Adds a marker to the map at the specified position with custom properties.
    • Example:
      var point = new RoutePoint("point1", new PositionPoint(37.7749f, -122.4194f), "San Francisco", "<svg>...</svg>", "<h3>San Francisco</h3>");
      await mapComponent.AddPoint(point);
      
  2. RemovePoint(string id):

    • Removes a marker from the map by its ID.
    • Example:
      await mapComponent.RemovePoint("point1");
      
  3. CenterMap(PositionPoint point):

    • Centers the map on the specified coordinates.
    • Example:
      var point = new PositionPoint(37.7749f, -122.4194f);
      await mapComponent.CenterMap(point);
      
  4. ClearMap():

    • Removes all markers and routes from the map.
    • Example:
      await mapComponent.ClearMap();
      
  5. ShowRoute(PositionPoint startPoint, PositionPoint endPoint, string travelMode = "DRIVING", string routeId = "Route", string color = "#1a73e8"):

    • Displays a route between two points.
    • Supported travelMode values: "DRIVING", "WALKING", "BICYCLING", "TRANSIT".
    • Example:
      var start = new PositionPoint(37.7749f, -122.4194f);
      var end = new PositionPoint(34.0522f, -118.2437f);
      await mapComponent.ShowRoute(start, end, "DRIVING", "route1", "red");
      
  6. ShowRouteWithWaypoints(IEnumerable<RoutePoint> points, string travelMode = "DRIVING", string routeId = "Route", string color = "#1a73e8"):

    • Displays a route with waypoints.
    • Example:
      var points = new List<RoutePoint>
      {
          new RoutePoint("point1", new PositionPoint(37.7749f, -122.4194f), "San Francisco", "", ""),
          new RoutePoint("point2", new PositionPoint(36.1699f, -115.1398f), "Las Vegas", "", "")
      };
      await mapComponent.ShowRouteWithWaypoints(points, "DRIVING", "route1", "red");
      
  7. HighlightMarker(string id):

    • Highlights a marker by its ID (e.g., changes its appearance).
    • Example:
      await mapComponent.HighlightMarker("point1");
      
  8. UnhighlightMarker(string id):

    • Removes highlighting from a marker by its ID.
    • Example:
      await mapComponent.UnhighlightMarker("point1");
      
  9. RemoveRoute(string routeId):

    • Removes route by its ID.
    • Example:
      await mapComponent.RemoveRoute("route1");
      
  10. SearchAddress(string address):

    • Forward geocoding. Returns a MapClickEventArgs with the coordinates, the formatted address and the broken-down details, or null when Google cannot resolve it.
    • Example:
      MapClickEventArgs found = await mapComponent.SearchAddress("1600 Amphitheatre Parkway, Mountain View, CA");
      
  11. SearchAddressAndCenter(string address):

    • Same as SearchAddress and centers the map on the result when it is found.
    • Example:
      MapClickEventArgs found = await mapComponent.SearchAddressAndCenter("Mountain View, CA");
      
  12. GetCenter():

    • Returns the current center of the map as a PositionPoint without geocoding it, or null when the map is not ready.
    • Example:
      PositionPoint center = await mapComponent.GetCenter();
      
  13. RefreshCenter():

    • Forces an OnCenterChanged invocation with the current center. Useful after centering the map from code, because programmatic centering does not raise the event.
    • Example:
      await mapComponent.CenterMap(point);
      await mapComponent.RefreshCenter();
      
  14. EnableCenterPin() / DisableCenterPin():

    • Turns the center pin on or off at runtime. It is enabled automatically when ShowCenterPin is true or OnCenterChanged has a delegate.
    • Example:
      await mapComponent.DisableCenterPin();
      

Picking a location with the center pin

The center pin keeps the pin fixed in the middle of the map and lets the user move the map underneath it. Every pan or zoom reports the new position, so the last one received is the chosen location.

<GoogleMapComponent ApiKey="@ApiKey"
                    ShowCenterPin="true"
                    StartZoomLevel="18"
                    CenterChangedDebounceMilliseconds="500"
                    OnCenterChanged="OnCenterChangedCallback" />

@code {
    private void OnCenterChangedCallback(MapClickEventArgs args)
    {
        Console.WriteLine($"Lat: {args.Point?.Latitude}, Lng: {args.Point?.Longitude}");
        Console.WriteLine($"Address: {args.Address}");
    }
}

The event is raised on dragend and zoom_changed, not on every frame of the gesture, so one movement produces one call. Each call reverse geocodes the center unless GeocodeCenterOnMove is false.

Example: Full Implementation

Below is an example of a Razor page that uses the GoogleMapComponent to display a map, add a marker, and show a route.

@page "/map-example"
@using BlazorBasics.Maps.Google
@using BlazorBasics.Maps.Google.Models

<h3>Example Interactive Map</h3>

<GoogleMapComponent @ref="mapComponent"
                  ApiKey="TU_CLAVE_DE_API_DE_GOOGLE_MAPS"
                  MapId="TU_ID_DE_MAPA_PERSONALIZADO"
                  StartZoomLevel=10
                  OnMapReady="@OnMapReadyCallback"
                  OnClick="@OnMapClickCallback" />

<p>@clickedAddress</p>

@code {
    private GoogleMapComponent mapComponent = default!;
    private string clickedAddress = "Haz clic en el mapa para ver la direcci�n aqu�.";

    private async Task OnMapReadyCallback()
    {
        // Add marker
        var sanFranciscoPoint = new RoutePoint(
            id: "SF",
            point: new PositionPoint(37.7749f, -122.4194f),
            description: "San Francisco",
            svgIcon: "<svg width='24' height='24'><circle cx='12' cy='12' r='10' fill='blue'/></svg>",
            htmlContent: "<h3>San Francisco</h3>"
        );
        await mapComponent.AddPoint(sanFranciscoPoint);
        await mapComponent.RemovePoint("marker-id");

        // Centrer el map
        await mapComponent.CenterMap(new PositionPoint(37.6f, -120f));

        // Show route
        var start = new PositionPoint(37.7749f, -122.4194f); // San Francisco
        var end = new PositionPoint(34.0522f, -118.2437f);   // Los Angeles
        await mapComponent.ShowRoute(startPoint: start, endPoint: end, travelMode: "DRIVING", routeId: "route-id", color: "red");
        var points = new List<RoutePoint>
        {
            new RoutePoint(id: "SF", point: new PositionPoint(37.7749f, -122.4194f), description: "San Francisco", svgIcon: "", htmlContent: "", color: "red"),
            new RoutePoint(id: "LV", point: new PositionPoint(36.1699f, -115.1398f), description: "Las Vegas", svgIcon: "", htmlContent: "", color: "yellow"),
            new RoutePoint(id: "LA", point: new PositionPoint(34.0522f, -118.2437f), description: "Los Angeles", svgIcon: "", htmlContent: "", color: "green")
        };
        await mapComponent.ShowRouteWithWaypoints(points, travelMode: "DRIVING", routeId: "route-id", color: "green");
        await mapComponent.RemoveRoute("route-id");
        await mapComponent.HighlightMarker("marker-id", color: "black");
        await mapComponent.UnhighlightMarker("marker-id");
        await mapComponent.ClearMap();
    }

    private void OnMapClickCallback(MapClickEventArgs args)
    {
        if (args.PointId is not null)
        {
            clickedAddress = $"Click on marker ID: {args.PointId}.";
        }
        if (args.Address is not null)
        {
            clickedAddress = $"Clic address: {args.Address}";
            // Also from details ...
            // var country = args.Details?.Country;
        }
        else
        {
            clickedAddress = "Can't get the address.";
        }
        StateHasChanged();
    }
}

Notes

  • JavaScript Interop: The library relies on the loadGoogleMaps.js file for Google Maps API interactions. Ensure this file is correctly implemented and includes functions like load, initMap, addPoint, removePoint, centerMap, cleanMap, showRoute, showRouteWithWaypoints, highlightMarker, unhighlightMarker, enableMapClick, disableMapClick, enableCenterPin, disableCenterPin, refreshCenter, getCenter and geocodeAddress.
  • Error Handling: The component checks for a valid ApiKey. If missing, it displays a message: "API Key is required to load Google Maps.".
  • MapId: Optional. Markers and routes use advanced markers, which Google only renders on a map created with a map ID, so a console warning is written when AddPoint, ShowRoute or ShowRouteWithWaypoints run without it. The center pin is a DOM overlay and works without it.
  • Coordinate Validation: The PositionPoint struct validates latitude and longitude to prevent invalid coordinates.
  • Custom Styling: Use the MapId parameter to apply custom map styles created in the Google Cloud Console.
  • Geocoding: SearchAddress, SearchAddressAndCenter and the address returned by OnClick and OnCenterChanged use the Geocoding API, billed separately from the map loads. Set GeocodeCenterOnMove to false when you only need coordinates.

Troubleshooting

  • Map Not Loading: Verify that the ApiKey is valid and the Maps JavaScript API is enabled in the Google Cloud Console.
  • Markers Not Showing: Advanced markers need a MapId. Check the browser console for the warning.
  • No Address In The Callbacks: Enable the Geocoding API for the same key in the Google Cloud Console.

Contributing

If you encounter issues or have suggestions for improvements, please submit an issue or pull request to the repository hosting this library.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.3.3 160 8/4/2026
1.2.2 183 1/16/2026
1.2.1 135 1/5/2026
1.2.0 357 11/17/2025
1.1.5 292 11/10/2025
1.1.4 229 10/22/2025
1.0.3 234 10/14/2025
1.0.2 234 10/13/2025
1.0.1 243 10/3/2025
1.0.0 229 10/1/2025

Added a fixed center pin: ShowCenterPin, CenterPinSvgIcon, GeocodeCenterOnMove, CenterChangedDebounceMilliseconds and OnCenterChanged report the map center after every pan or zoom, so the user moves the map instead of the marker.
Added forward geocoding with SearchAddress and SearchAddressAndCenter, plus GetCenter and RefreshCenter.
MapId is now optional. It is still needed to render advanced markers and routes, and a console warning is written when it is missing.
ClearMap no longer loses the click, popup and center pin listeners when the map is reinitialized.