BlazorBasics.Maps.Google
1.1.4
dotnet add package BlazorBasics.Maps.Google --version 1.1.4
NuGet\Install-Package BlazorBasics.Maps.Google -Version 1.1.4
<PackageReference Include="BlazorBasics.Maps.Google" Version="1.1.4" />
<PackageVersion Include="BlazorBasics.Maps.Google" Version="1.1.4" />
<PackageReference Include="BlazorBasics.Maps.Google" />
paket add BlazorBasics.Maps.Google --version 1.1.4
#r "nuget: BlazorBasics.Maps.Google, 1.1.4"
#:package BlazorBasics.Maps.Google@1.1.4
#addin nuget:?package=BlazorBasics.Maps.Google&version=1.1.4
#tool nuget:?package=BlazorBasics.Maps.Google&version=1.1.4
Blazor Google Maps 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, and highlighting markers.
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
Install the NuGet Package:
- Install the
BlazorBasics.Maps.GoogleNuGet package in your Blazor project using the Package Manager or the .NET CLI:dotnet add package BlazorBasics.Maps.Google
- Install the
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%; }
Include the Component in Your Razor Page:
- Add the
GoogleMapComponentto your Razor page and provide the required parameters (ApiKeyandMapId).
- Add the
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"
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 |
Required. A custom map ID for styled maps. |
OnMapReady |
EventCallback |
Optional. A callback invoked when the map is fully loaded and ready to use. |
OnClick |
EventCallback<MapClickEventArgs> |
Optional. A callback that is invoked when the map or a marker is clicked. |
| It returns the coordinates and address details. |
Models
The library includes two main models:
PositionPoint:- Represents a geographic coordinate with
LatitudeandLongitude. - 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);
- Represents a geographic coordinate with
RoutePoint:- Represents a marker on the map with additional metadata.
- Properties:
- Id: Unique identifier for the point.
- Position: A
PositionPointspecifying 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. Defaultnew 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:
CIRCLEFORWARD_CLOSED_ARROWFORWARD_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
ArrowTypewith display arrow type. DefaultArrowType.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:
- PointId: The marker ID if one was clicked; otherwise, null.
- Point: A PositionPoint with the click coordinates.
- Address: A string containing the address formatted at the point of the click (reverse geocoding).
- Details: An AddressDetails object with the address components broken down.
AddressDetails- Contains the broken-down components of an address obtained from reverse geocoding.
- Properties:
- Street Number
- Route
- Neighborhood
- Locality
- Administrative Area (state/province)
- Country
- Postal Code.
Available Methods
The GoogleMapComponent provides the following methods to interact with the map:
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);
RemovePoint(string id):- Removes a marker from the map by its ID.
- Example:
await mapComponent.RemovePoint("point1");
CenterMap(PositionPoint point):- Centers the map on the specified coordinates.
- Example:
var point = new PositionPoint(37.7749f, -122.4194f); await mapComponent.CenterMap(point);
ClearMap():- Removes all markers and routes from the map.
- Example:
await mapComponent.ClearMap();
ShowRoute(PositionPoint startPoint, PositionPoint endPoint, string travelMode = "DRIVING", string routeId = "Route", string color = "#1a73e8"):- Displays a route between two points.
- Supported
travelModevalues:"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");
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");
HighlightMarker(string id):- Highlights a marker by its ID (e.g., changes its appearance).
- Example:
await mapComponent.HighlightMarker("point1");
UnhighlightMarker(string id):- Removes highlighting from a marker by its ID.
- Example:
await mapComponent.UnhighlightMarker("point1");
RemoveRoute(string routeId):- Removes route by its ID.
- Example:
await mapComponent.RemoveRoute("route1");
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"
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.jsfile for Google Maps API interactions. Ensure this file is correctly implemented and includes functions likeload,initMap,addPoint,removePoint,centerMap,cleanMap,showRoute,showRouteWithWaypoints,highlightMarker,unhighlightMarker,enableMapClickanddisableMapClick. - Error Handling: The component checks for a valid
ApiKey. If missing, it displays a message: "API Key is required to load Google Maps.". - Error Handling: The component checks for a valid
MapId. If missing, it displays a message: "MapId is required to identify the map instance.". - Coordinate Validation: The
PositionPointstruct validates latitude and longitude to prevent invalid coordinates. - Custom Styling: Use the
MapIdparameter to apply custom map styles created in the Google Cloud Console.
Troubleshooting
- Map Not Loading: Verify that the
ApiKeyandMapIdare valid and the Maps JavaScript API is enabled 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 | Versions 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 was computed. 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. |
-
net9.0
- Microsoft.AspNetCore.Components.Web (>= 9.0.10)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Improved how to show the arrows fro the directions. Improve how to clean map fro full clearing the enviroment. Update dependencies.