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
<PackageReference Include="BlazorBasics.Maps.Google" Version="1.3.3" />
<PackageVersion Include="BlazorBasics.Maps.Google" Version="1.3.3" />
<PackageReference Include="BlazorBasics.Maps.Google" />
paket add BlazorBasics.Maps.Google --version 1.3.3
#r "nuget: BlazorBasics.Maps.Google, 1.3.3"
#:package BlazorBasics.Maps.Google@1.3.3
#addin nuget:?package=BlazorBasics.Maps.Google&version=1.3.3
#tool nuget:?package=BlazorBasics.Maps.Google&version=1.3.3
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
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"
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
LatitudeandLongitude. - Implement from
ILatLongandIEquatable<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);
- 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:
- 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
IAddressDetailsobject 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:
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");
SearchAddress(string address):- Forward geocoding. Returns a
MapClickEventArgswith the coordinates, the formatted address and the broken-down details, ornullwhen Google cannot resolve it. - Example:
MapClickEventArgs found = await mapComponent.SearchAddress("1600 Amphitheatre Parkway, Mountain View, CA");
- Forward geocoding. Returns a
SearchAddressAndCenter(string address):- Same as
SearchAddressand centers the map on the result when it is found. - Example:
MapClickEventArgs found = await mapComponent.SearchAddressAndCenter("Mountain View, CA");
- Same as
GetCenter():- Returns the current center of the map as a
PositionPointwithout geocoding it, ornullwhen the map is not ready. - Example:
PositionPoint center = await mapComponent.GetCenter();
- Returns the current center of the map as a
RefreshCenter():- Forces an
OnCenterChangedinvocation 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();
- Forces an
EnableCenterPin()/DisableCenterPin():- Turns the center pin on or off at runtime. It is enabled automatically when
ShowCenterPinis true orOnCenterChangedhas a delegate. - Example:
await mapComponent.DisableCenterPin();
- Turns the center pin on or off at runtime. It is enabled automatically when
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.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,enableMapClick,disableMapClick,enableCenterPin,disableCenterPin,refreshCenter,getCenterandgeocodeAddress. - 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,ShowRouteorShowRouteWithWaypointsrun without it. The center pin is a DOM overlay and works without it. - 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. - Geocoding:
SearchAddress,SearchAddressAndCenterand the address returned byOnClickandOnCenterChangeduse the Geocoding API, billed separately from the map loads. SetGeocodeCenterOnMoveto false when you only need coordinates.
Troubleshooting
- Map Not Loading: Verify that the
ApiKeyis 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 | 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 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. |
-
net10.0
- BlazorBasics.Maps.Entities (>= 1.2.0)
- Microsoft.AspNetCore.Components.Web (>= 10.0.2)
-
net9.0
- BlazorBasics.Maps.Entities (>= 1.2.0)
- Microsoft.AspNetCore.Components.Web (>= 9.0.12)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
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.