### Configure BlazorGoogleMaps Dependency Injection Source: https://context7.com/rungwiroon/blazorgooglemaps/llms.txt Sets up BlazorGoogleMaps in your application's startup, requiring a Google API key. Supports simple key registration, advanced configuration with specific libraries and versions, and custom key services for asynchronous retrieval. ```csharp // Program.cs (Blazor WASM or Blazor Server) using GoogleMapsComponents; using GoogleMapsComponents.Maps; var builder = WebApplication.CreateBuilder(args); // Option 1: Simple API key registration builder.Services.AddBlazorGoogleMaps("YOUR_GOOGLE_API_KEY"); // Option 2: Advanced configuration with specific libraries and version builder.Services.AddBlazorGoogleMaps(new MapApiLoadOptions("YOUR_GOOGLE_API_KEY") { Version = "beta", Libraries = "places,visualization,drawing,marker", Language = "en", Region = "US" }); // Option 3: Custom key service for async key retrieval builder.Services.AddScoped(); var app = builder.Build(); app.Run(); ``` -------------------------------- ### Using Open Iconic Standalone Source: https://github.com/rungwiroon/blazorgooglemaps/blob/master/Demos/ServerSideDemo/wwwroot/css/open-iconic/README.md Provides instructions for using Open Iconic icons independently without a specific framework. It involves linking the default stylesheet and utilizing the 'oi' class with the 'data-glyph' attribute. ```html ``` ```html ``` -------------------------------- ### Calculate and Display Routes with Blazor Google Maps Directions Service (C#) Source: https://context7.com/rungwiroon/blazorgooglemaps/llms.txt This snippet shows how to initialize the Google Maps component, set up the Directions Service and Renderer, and handle user input to calculate routes. It displays route information, distance, duration, and step-by-step directions. Dependencies include the GoogleMapsComponents NuGet package. It takes origin, destination, and travel mode as input and outputs route details and instructions. ```csharp @page "/directions" @using GoogleMapsComponents @using GoogleMapsComponents.Maps @implements IAsyncDisposable

Route Information:

@_routeInfo

@if (_steps.Any()) {

Directions:

    @foreach (var step in _steps) {
  1. @((MarkupString)step)
  2. }
}
@code { private GoogleMap _map; private DirectionsService _directionsService; private DirectionsRenderer _directionsRenderer; private string _origin = "Bangkok, Thailand"; private string _destination = "Pattaya, Thailand"; private string _travelMode = "DRIVING"; private string _routeInfo = ""; private List _steps = new(); private MapOptions _mapOptions = new MapOptions() { Zoom = 7, Center = new LatLngLiteral(13.7563, 100.5018), MapTypeId = MapTypeId.Roadmap }; private async Task AfterMapRender() { _directionsService = await DirectionsService.CreateAsync(_map.JsRuntime); var rendererOptions = new DirectionsRendererOptions { Map = _map.InteropObject, SuppressMarkers = false, DraggableRoute = true }; _directionsRenderer = await DirectionsRenderer.CreateAsync(_map.JsRuntime, rendererOptions); } private async Task CalculateRoute() { var travelModeEnum = Enum.Parse(_travelMode); var request = new DirectionsRequest { Origin = _origin, Destination = _destination, TravelMode = travelModeEnum, ProvideRouteAlternatives = true, OptimizeWaypoints = true }; try { var result = await _directionsService.Route(request); if (result.Status == DirectionsStatus.Ok && result.Routes.Length > 0) { // Display route on map await _directionsRenderer.SetDirections(result); var route = result.Routes[0]; var leg = route.Legs[0]; _routeInfo = $"Distance: {leg.Distance.Text}, Duration: {leg.Duration.Text}"; // Extract step-by-step instructions _steps = leg.Steps.Select(s => s.Instructions).ToList(); } else { _routeInfo = $"Route calculation failed: {result.Status}"; _steps.Clear(); } } catch (Exception ex) { _routeInfo = $"Error: {ex.Message}"; } } private async Task ClearRoute() { await _directionsRenderer.SetDirections(null); _routeInfo = ""; _steps.Clear(); } public async ValueTask DisposeAsync() { _directionsService?.Dispose(); _directionsRenderer?.Dispose(); } } ``` -------------------------------- ### Basic Google Map Component - Blazor Source: https://github.com/rungwiroon/blazorgooglemaps/blob/master/README.md Renders a basic Google Map using the `GoogleMap` component in Blazor. This snippet demonstrates how to initialize map options like zoom level, center coordinates, and map type, and includes an event handler for map initialization. ```blazor @page "/map" @using GoogleMapsComponents @using GoogleMapsComponents.Maps

Google Map

@functions { private GoogleMap _map1; private MapOptions mapOptions; protected override void OnInitialized() { mapOptions = new MapOptions() { Zoom = 13, Center = new LatLngLiteral() { Lat = 13.505892, Lng = 100.8162 }, MapTypeId = MapTypeId.Roadmap }; } private async Task AfterMapRender() { _bounds = await LatLngBounds.CreateAsync(_map1.JsRuntime); } } ``` -------------------------------- ### Include BlazorGoogleMaps JavaScript and Marker Clustering Source: https://github.com/rungwiroon/blazorgooglemaps/blob/master/README.md Includes the necessary JavaScript files for BlazorGoogleMaps and optional marker clustering functionality. The `objectManager.js` is essential for component interaction, while the marker clusterer script enhances map performance with many markers. ```html ``` ```html ``` -------------------------------- ### Using Open Iconic with Foundation Source: https://github.com/rungwiroon/blazorgooglemaps/blob/master/Demos/ServerSideDemo/wwwroot/css/open-iconic/README.md Details the integration of Open Iconic icons with the Foundation framework. This requires including the Foundation-specific stylesheet and applying the correct classes to span elements. ```html ``` ```html ``` -------------------------------- ### Blazor C#: Bulk Marker Management with MarkerList Source: https://context7.com/rungwiroon/blazorgooglemaps/llms.txt This C# Blazor component demonstrates how to create, update, and toggle the visibility of a large number of markers on a Google Map using the `MarkerList` class. It requires the `GoogleMapsComponents` library. The component takes map options, and event handlers for button clicks to perform bulk operations. ```csharp @page "/marker-list" @using GoogleMapsComponents @using GoogleMapsComponents.Maps @using GoogleMapsComponents.Maps.Extension @implements IAsyncDisposable @code { private GoogleMap _map; private MarkerList _markerList; private MapOptions _mapOptions = new MapOptions() { Zoom = 10, Center = new LatLngLiteral(13.505892, 100.8162), MapTypeId = MapTypeId.Roadmap }; private async Task AfterMapRender() { await AddBulkMarkers(); } private async Task AddBulkMarkers() { var markerOptions = new Dictionary(); var random = new Random(); for (int i = 0; i < 100; i++) { markerOptions[$"marker_{i}"] = new MarkerOptions { Position = new LatLngLiteral( 13.505892 + (random.NextDouble() - 0.5) * 0.5, 100.8162 + (random.NextDouble() - 0.5) * 0.5 ), Map = _map.InteropObject, Title = $"Marker {i}", Label = new MarkerLabel { Text = i.ToString() } }; } _markerList = await MarkerList.CreateAsync(_map.JsRuntime, markerOptions); Console.WriteLine($"Created {_markerList.Markers.Count} markers"); } private async Task UpdatePositions() { var newPositions = new Dictionary(); var random = new Random(); foreach (var key in _markerList.Markers.Keys) { newPositions[key] = new LatLngLiteral( 13.505892 + (random.NextDouble() - 0.5) * 0.5, 100.8162 + (random.NextDouble() - 0.5) * 0.5 ); } await _markerList.SetPositions(newPositions); Console.WriteLine("All marker positions updated"); } private async Task ToggleVisibility() { var visibilities = new Dictionary(); foreach (var key in _markerList.Markers.Keys) { var currentVisibility = await _markerList.Markers[key].GetVisible(); visibilities[key] = !currentVisibility; } await _markerList.SetVisibles(visibilities); } public async ValueTask DisposeAsync() { if (_markerList != null) { await _markerList.RemoveAllAsync(); } } } ``` -------------------------------- ### Blazor Drawing Manager for Google Maps Source: https://context7.com/rungwiroon/blazorgooglemaps/llms.txt This C# code snippet shows a Blazor component that sets up a Google Map with a drawing manager. It allows users to select different drawing modes (marker, polyline, polygon, circle) and listens for 'overlaycomplete' events to track drawn shapes. Dependencies include GoogleMapsComponents and System.Collections.Generic. Inputs are user clicks and map initialization. Outputs include console logs and a count of drawn shapes. ```csharp @page "/drawing-manager" @using GoogleMapsComponents @using GoogleMapsComponents.Maps @implements IAsyncDisposable

Drawn Shapes: @_drawnShapes.Count

@code { private GoogleMap _map; private DrawingManager _drawingManager; private List _drawnShapes = new(); private MapOptions _mapOptions = new MapOptions() { Zoom = 13, Center = new LatLngLiteral(13.505892, 100.8162), MapTypeId = MapTypeId.Roadmap }; private async Task AfterMapRender() { var drawingOptions = new DrawingManagerOptions { DrawingMode = OverlayType.MARKER, Map = _map.InteropObject, DrawingControl = true, DrawingControlOptions = new DrawingControlOptions { Position = ControlPosition.TOP_CENTER, DrawingModes = new[] { OverlayType.MARKER, OverlayType.POLYLINE, OverlayType.POLYGON, OverlayType.CIRCLE, OverlayType.RECTANGLE } }, MarkerOptions = new MarkerOptions { Draggable = true }, PolylineOptions = new PolylineOptions { StrokeColor = "#FF0000", StrokeWeight = 4, Editable = true }, PolygonOptions = new PolygonOptions { StrokeColor = "#00FF00", FillColor = "#00FF00", FillOpacity = 0.35, Editable = true }, CircleOptions = new CircleOptions { StrokeColor = "#0000FF", FillColor = "#0000FF", FillOpacity = 0.35, Editable = true } }; _drawingManager = await DrawingManager.CreateAsync(_map.JsRuntime, drawingOptions); // Listen for overlay complete events await _drawingManager.AddListener("overlaycomplete", async e => { _drawnShapes.Add($"{e.Type} at {DateTime.Now:HH:mm:ss}"); StateHasChanged(); Console.WriteLine($"Shape drawn: {e.Type}"); }); } private async Task EnableMarkerMode() { await _drawingManager.SetDrawingMode(OverlayType.MARKER); } private async Task EnablePolylineMode() { await _drawingManager.SetDrawingMode(OverlayType.POLYLINE); } private async Task EnablePolygonMode() { await _drawingManager.SetDrawingMode(OverlayType.POLYGON); } private async Task EnableCircleMode() { await _drawingManager.SetDrawingMode(OverlayType.CIRCLE); } private async Task DisableDrawing() { await _drawingManager.SetDrawingMode(null); } public async ValueTask DisposeAsync() { _drawingManager?.Dispose(); } } ``` -------------------------------- ### HTML Script Reference for BlazorGoogleMaps Source: https://context7.com/rungwiroon/blazorgooglemaps/llms.txt Includes the necessary JavaScript reference in your HTML file to enable BlazorGoogleMaps interop functionality. This script is essential for the library to communicate with the Google Maps API. ```html BlazorGoogleMaps Demo ``` -------------------------------- ### Using Open Iconic SVG Sprite Source: https://github.com/rungwiroon/blazorgooglemaps/blob/master/Demos/ServerSideDemo/wwwroot/css/open-iconic/README.md Illustrates using Open Iconic's SVG sprite for efficient icon display. It suggests adding classes to the SVG and use tags for styling and unique identification. Basic CSS for sizing and coloring icons is also provided. ```html ``` ```css .icon { width: 16px; height: 16px; } ``` ```css .icon-account-login { fill: #f00; } ``` -------------------------------- ### Display Info Windows on Marker Click in Blazor Source: https://context7.com/rungwiroon/blazorgooglemaps/llms.txt This C# code snippet demonstrates how to create markers on a Google Map in a Blazor application and display custom, HTML-rich information windows when these markers are clicked. It manages multiple markers and info windows, ensuring only one is open at a time, and handles their disposal. ```csharp @page "/infowindows" @using GoogleMapsComponents @using GoogleMapsComponents.Maps @implements IAsyncDisposable @code { private GoogleMap _map; private List _markers = new(); private List _infoWindows = new(); private MapOptions _mapOptions = new MapOptions() { Zoom = 13, Center = new LatLngLiteral(13.505892, 100.8162), MapTypeId = MapTypeId.Roadmap }; private async Task AfterMapRender() { await AddMarkerWithInfo(); } private async Task AddMarkerWithInfo() { var position = new LatLngLiteral( 13.505892 + _markers.Count * 0.01, 100.8162 + _markers.Count * 0.01 ); // Create marker var marker = await Marker.CreateAsync(_map.JsRuntime, new MarkerOptions { Position = position, Map = _map.InteropObject, Title = $"Location {_markers.Count + 1}" }); // Create info window with rich HTML content var infoContent = $"\
\

Location {_markers.Count + 1}

\

Latitude: {position.Lat:F5}

\

Longitude: {position.Lng:F5}

\

Time: {DateTime.Now:HH:mm:ss}

\ \
"; var infoWindow = await InfoWindow.CreateAsync(_map.JsRuntime, new InfoWindowOptions { Content = infoContent, MaxWidth = 300 }); // Open info window on marker click await marker.AddListener("click", async e => { // Close all other info windows foreach (var iw in _infoWindows) { await iw.Close(); } // Open this info window await infoWindow.Open(_map.InteropObject, marker); }); _markers.Add(marker); _infoWindows.Add(infoWindow); // Auto-open the first info window if (_markers.Count == 1) { await infoWindow.Open(_map.InteropObject, marker); } } public async ValueTask DisposeAsync() { foreach (var marker in _markers) { marker.Dispose(); } foreach (var infoWindow in _infoWindows) { infoWindow.Dispose(); } } } ``` -------------------------------- ### Render Basic Google Map Component in Blazor Source: https://context7.com/rungwiroon/blazorgooglemaps/llms.txt Demonstrates how to render a basic Google Map within a Blazor component. It configures the map's center, zoom level, and map type, and includes an event handler for when the map is fully initialized. ```csharp @page "/map" @using GoogleMapsComponents @using GoogleMapsComponents.Maps;

Google Map

@code { private GoogleMap _map; private MapOptions _mapOptions; protected override void OnInitialized() { _mapOptions = new MapOptions() { Zoom = 13, Center = new LatLngLiteral(13.505892, 100.8162), MapTypeId = MapTypeId.Roadmap, DisableDefaultUI = false, ZoomControl = true, StreetViewControl = true }; } private async Task AfterMapRender() { // Map is fully initialized, perform additional setup var center = await _map.InteropObject.GetCenter(); var zoom = await _map.InteropObject.GetZoom(); Console.WriteLine($"Map initialized at {center.Lat}, {center.Lng} with zoom {zoom}"); } } ``` -------------------------------- ### Blazor: Create Marker List with Options Source: https://github.com/rungwiroon/blazorgooglemaps/wiki/MarkerList-for-multi-markets-manipulation This snippet shows how to create a list of markers for a Google Map in Blazor. It uses `MarkerList.CreateAsync` to initialize markers with specific positions, icons, and titles, based on a provided list of stops. The `Visible` property is initially set to `false` for performance with a large number of markers. ```csharp stopMarkerList = await MarkerList.CreateAsync ( gtfsMap.JsRuntime, Stops.ToDictionary(s => s.Id, s => new MarkerOptions { Position = new LatLngLiteral(s.Longitude, s.Latitude), Map = map.InteropObject, Title = s.Code, Icon = "/images/stop.png", Visible = false }) ); ``` -------------------------------- ### Using Open Iconic with Bootstrap Source: https://github.com/rungwiroon/blazorgooglemaps/blob/master/Demos/ServerSideDemo/wwwroot/css/open-iconic/README.md Shows how to integrate Open Iconic icons when using Bootstrap. This involves linking the Bootstrap-specific stylesheet and using the provided icon classes in span tags. ```html ``` ```html ``` -------------------------------- ### Using Open Iconic SVG Sprite Source: https://github.com/rungwiroon/blazorgooglemaps/blob/master/Demos/ClientSideDemo/wwwroot/css/open-iconic/README.md Shows how to implement icons using Open Iconic's SVG sprite for efficient loading. It involves referencing an icon from a single SVG file using the 'use' tag and styling it with CSS. This approach is recommended for easier styling and better performance compared to individual SVG files. ```html ``` ```css .icon { width: 16px; height: 16px; } .icon-account-login { fill: #f00; } ``` -------------------------------- ### Configure Google API Key with Service - C# Source: https://github.com/rungwiroon/blazorgooglemaps/blob/master/README.md Configures the Google Maps API key using a service in Blazor. This is the recommended approach for managing API keys securely. It involves registering a service that provides the API key to the BlazorGoogleMaps library. ```csharp services.AddBlazorGoogleMaps("YOUR_KEY_GOES_HERE"); ``` ```csharp services.AddBlazorGoogleMaps(new GoogleMapsComponents.Maps.MapApiLoadOptions("YOUR_KEY_GOES_HERE") { Version = "beta", Libraries = "places,visualization,drawing,marker", }); ``` ```csharp services.AddScoped(); ``` -------------------------------- ### Using Open Iconic SVGs Source: https://github.com/rungwiroon/blazorgooglemaps/blob/master/Demos/ServerSideDemo/wwwroot/css/open-iconic/README.md Demonstrates how to embed Open Iconic SVGs directly into HTML, similar to standard image tags. Ensure the 'alt' attribute is used for accessibility. ```html icon name ``` -------------------------------- ### Blazor Heatmap Layer for Data Visualization Source: https://context7.com/rungwiroon/blazorgooglemaps/llms.txt This C# code snippet demonstrates how to create and manage a heatmap layer on a Google Map in a Blazor application. It utilizes the GoogleMapsComponents library to generate random data points, configure heatmap options like radius and gradient, and provides methods to dynamically update the heatmap's appearance. The component also handles map initialization and disposal of the heatmap layer. ```csharp @page "/heatmap" @using GoogleMapsComponents @using GoogleMapsComponents.Maps @using GoogleMapsComponents.Maps.Coordinates @using GoogleMapsComponents.Maps.Visualization @implements IAsyncDisposable @code { private GoogleMap _map; private HeatmapLayer _heatmapLayer; private bool _isVisible = true; private int _currentRadius = 20; private MapOptions _mapOptions = new MapOptions() { Zoom = 13, Center = new LatLngLiteral(-33.848588, 151.209834), MapTypeId = MapTypeId.Satellite }; private async Task AfterMapRender() { // Generate random data points var random = new Random(); var dataPoints = new List(); for (int i = 0; i < 200; i++) { dataPoints.Add(new LatLngLiteral( -33.848588 + (random.NextDouble() - 0.5) * 0.1, 151.209834 + (random.NextDouble() - 0.5) * 0.1 )); } var heatmapOptions = new HeatmapLayerOptions { Data = dataPoints.ToArray(), Map = _map.InteropObject, Radius = 20, Opacity = 0.6, Gradient = new[] { "rgba(0, 255, 255, 0)", "rgba(0, 255, 255, 1)", "rgba(0, 191, 255, 1)", "rgba(0, 127, 255, 1)", "rgba(0, 63, 255, 1)", "rgba(0, 0, 255, 1)", "rgba(0, 0, 223, 1)", "rgba(0, 0, 191, 1)", "rgba(0, 0, 159, 1)", "rgba(0, 0, 127, 1)", "rgba(63, 0, 91, 1)", "rgba(127, 0, 63, 1)", "rgba(191, 0, 31, 1)", "rgba(255, 0, 0, 1)" } }; _heatmapLayer = await HeatmapLayer.CreateAsync(_map.JsRuntime, heatmapOptions); } private async Task ToggleHeatmap() { _isVisible = !_isVisible; await _heatmapLayer.SetMap(_isVisible ? _map.InteropObject : null); } private async Task ChangeGradient() { var gradient = new[] { "rgba(255, 255, 0, 0)", "rgba(255, 255, 0, 1)", "rgba(255, 128, 0, 1)", "rgba(255, 0, 0, 1)" }; await _heatmapLayer.SetOptions(new HeatmapLayerOptions { Gradient = gradient }); } private async Task ChangeRadius() { _currentRadius = _currentRadius == 20 ? 40 : 20; await _heatmapLayer.SetOptions(new HeatmapLayerOptions { Radius = _currentRadius }); } public async ValueTask DisposeAsync() { _heatmapLayer?.Dispose(); } } ``` -------------------------------- ### Blazor C# Places Autocomplete and Details Service Source: https://context7.com/rungwiroon/blazorgooglemaps/llms.txt This C# code implements a Blazor component for Google Maps Places Autocomplete and Place Details. It uses the GoogleMapsComponents library to interact with the Google Maps JavaScript API. It handles user input for search, fetches autocomplete suggestions, retrieves detailed information for selected places, and displays markers on the map. Dependencies include the GoogleMapsComponents library and a valid Google Maps API key. ```csharp @page "/places-autocomplete" @using GoogleMapsComponents @using GoogleMapsComponents.Maps @using GoogleMapsComponents.Maps.Places @implements IAsyncDisposable
@if (_suggestions.Any()) {

Suggestions:

    @foreach (var suggestion in _suggestions) {
  • @suggestion.Description
  • }
}

@_statusMessage

@code { private GoogleMap _map; private AutocompleteService _autocompleteService; private PlacesService _placesService; private AutocompleteSessionToken _token; private List _markers = new(); private string _searchInput = ""; private List _suggestions = new(); private string _statusMessage = ""; private MapOptions _mapOptions = new MapOptions() { Zoom = 13, Center = new LatLngLiteral(-33.8688, 151.2195), MapTypeId = MapTypeId.Roadmap }; private async Task AfterMapRender() { _autocompleteService = await AutocompleteService.CreateAsync(_map.JsRuntime); _placesService = await PlacesService.CreateAsync(_map.JsRuntime, _map.InteropObject); _token = await AutocompleteSessionToken.CreateAsync(_map.JsRuntime); } private async Task SearchPlaces() { if (string.IsNullOrWhiteSpace(_searchInput)) { _statusMessage = "Please enter a search term"; return; } var request = new AutocompletionRequest { Input = _searchInput, SessionToken = _token }; var response = await _autocompleteService.GetPlacePredictions(request); if (response.Status == PlaceServiceStatus.Ok) { _suggestions = response.Predictions.ToList(); _statusMessage = $"Found {@_suggestions.Count} suggestions"; } else { _statusMessage = $"Search failed: {response.Status}"; _suggestions.Clear(); } } private async Task GetPlaceDetails(string placeId) { var request = new PlaceDetailsRequest { PlaceId = placeId, Fields = new[] { "address_components", "formatted_address", "geometry", "name", "place_id" }, SessionToken = _token }; var place = await _placesService.GetDetails(request); if (place.Status == PlaceServiceStatus.Ok && place.Results?.Geometry?.Location != null) { var location = place.Results.Geometry.Location.Value; // Clear existing markers foreach (var marker in _markers) { await marker.SetMap(null); marker.Dispose(); } _markers.Clear(); // Create new marker var marker = await Marker.CreateAsync(_map.JsRuntime, new MarkerOptions { Position = location, Map = _map.InteropObject, Title = place.Results.FormattedAddress }); _markers.Add(marker); // Center and zoom to place await _map.InteropObject.SetCenter(location); await _map.InteropObject.SetZoom(15); _statusMessage = $"Showing: {place.Results.Name} - {place.Results.FormattedAddress}"; } else { _statusMessage = $"Failed to get place details: {place.Status}"; } // Refresh token after getting details _token?.Dispose(); _token = await AutocompleteSessionToken.CreateAsync(_map.JsRuntime); } private void ClearSuggestions() { _suggestions.Clear(); _statusMessage = ""; } public async ValueTask DisposeAsync() { foreach (var marker in _markers) { marker.Dispose(); } _token?.Dispose(); _autocompleteService?.Dispose(); _placesService?.Dispose(); } } ``` -------------------------------- ### Advanced Google Map with Blazor Markers - Blazor Source: https://github.com/rungwiroon/blazorgooglemaps/blob/master/README.md Renders an advanced Google Map with markers defined as Blazor components. This requires the `beta` version of the Google Maps API and a `MapId`. It shows how to iterate through marker data and bind events like clicks and drags to component actions. ```blazor @page "/map" @using GoogleMapsComponents @using GoogleMapsComponents.Maps

Google Map

@foreach (var markerRef in Markers) {

I am a blazor component

}
@code { private List Markers = [ new MarkerData { Id = 1, Lat = 13.505892, Lng = 100.8162 }, ]; private AdvancedGoogleMap? _map1; private MapOptions mapOptions =new MapOptions() { Zoom = 13, Center = new LatLngLiteral() { Lat = 13.505892, Lng = 100.8162 }, MapId = "DEMO_MAP_ID", //required for blazor markers MapTypeId = MapTypeId.Roadmap }; public class MarkerData { public int Id { get; set; } public double Lat { get; set; } public double Lng { get; set; } public bool Clickable { get; set; } = true; public bool Draggable { get; set; } public bool Active { get; set; } public void UpdatePosition(LatLngLiteral position) { Lat = position.Lat; Lng = position.Lng; } } } ``` -------------------------------- ### Blazor Marker Clustering with Google Maps Source: https://context7.com/rungwiroon/blazorgooglemaps/llms.txt This C# code snippet shows how to implement marker clustering for Google Maps in a Blazor application. It utilizes the GoogleMapsComponents library to render markers and the MarkerClustering utility to group them. The component supports enabling and disabling clustering, with options for zoom behavior and minimum cluster size. It requires the GoogleMapsComponents NuGet package. ```csharp @page "/marker-clustering" @using GoogleMapsComponents @using GoogleMapsComponents.Maps @implements IAsyncDisposable @foreach (var marker in Markers) {

Location @marker.Id

}
@code { private AdvancedGoogleMap _map; private MarkerClustering _markerClustering; private List Markers = new(); private MapOptions _mapOptions = new MapOptions() { Zoom = 4, Center = new LatLngLiteral(-33.848588, 151.209834), MapId = "clustering-map", MapTypeId = MapTypeId.Roadmap }; protected override void OnInitialized() { // Generate 100 random markers var random = new Random(); for (int i = 0; i < 100; i++) { Markers.Add(new MarkerData { Id = i, Lat = -33.848588 + random.NextDouble() * 10 - 5, Lng = 151.209834 + random.NextDouble() * 10 - 5 }); } } private async Task InvokeClustering() { if (_map.MapRef == null) return; if (_markerClustering == null) { _markerClustering = await MarkerClustering.CreateAsync( _map.MapRef.JsRuntime, _map.InteropObject, _map.Markers, new MarkerClustererOptions { ZoomOnClick = true, MaxZoom = 15, MinimumClusterSize = 2 }); } else { await _markerClustering.ClearMarkers(); await _markerClustering.AddMarkers(_map.Markers); } } private async Task ClearClustering() { if (_markerClustering != null) { await _markerClustering.ClearMarkers(); await _markerClustering.DisposeAsync(); _markerClustering = null; } } public async ValueTask DisposeAsync() { if (_markerClustering != null) { await _markerClustering.DisposeAsync(); } } public class MarkerData { public int Id { get; set; } public double Lat { get; set; } public double Lng { get; set; } } } ``` -------------------------------- ### Blazor Google Maps GeoJSON Data Layer Management Source: https://context7.com/rungwiroon/blazorgooglemaps/llms.txt This C# Blazor component demonstrates loading GeoJSON data onto a Google Map, styling it, and handling user interactions. It uses the GoogleMapsComponents library to interact with the Google Maps JavaScript API. Dependencies include the GoogleMapsComponents NuGet package. The component takes map configuration options and GeoJSON data as input and outputs styled map features with event listeners. ```csharp @page "/geojson" @using GoogleMapsComponents @using GoogleMapsComponents.Maps @using GoogleMapsComponents.Maps.Data @implements IAsyncDisposable @code { private GoogleMap _map; private List _features = new(); private MapOptions _mapOptions = new MapOptions() { Zoom = 4, Center = new LatLngLiteral(40, -100), MapTypeId = MapTypeId.Terrain }; private async Task AfterMapRender() { await LoadGeoJson(); } private async Task LoadGeoJson() { // Example GeoJSON - polygon representing a region var geoJson = @"{ "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [[ [-100, 40], [-100, 42], [-98, 42], [-98, 40], [-100, 40] ]] }, "properties": { "name": "Region 1", "population": 100000 } }, { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [[ [-98, 40], [-98, 42], [-96, 42], [-96, 40], [-98, 40] ]] }, "properties": { "name": "Region 2", "population": 200000 } } ] }"; var options = new GeoJsonOptions(); var feature = await _map.InteropObject.Data.AddGeoJson(geoJson, options); _features.Add(feature); // Style the data await _map.InteropObject.Data.SetStyle(new StyleOptions { FillColor = "blue", StrokeColor = "navy", StrokeWeight = 2, FillOpacity = 0.4 }); // Add click listener await _map.InteropObject.Data.AddListener("click", e => { Console.WriteLine($"Feature clicked: {e.Feature}"); }); } private async Task ChangeStyle() { await _map.InteropObject.Data.SetStyle(new StyleOptions { FillColor = "red", StrokeColor = "darkred", StrokeWeight = 3, FillOpacity = 0.6 }); } private async Task ClearData() { foreach (var feature in _features) { await _map.InteropObject.Data.RemoveFeature(feature.Id); } _features.Clear(); } public async ValueTask DisposeAsync() { await ClearData(); } } ``` -------------------------------- ### Create Marker Clusters in Blazor (C#) Source: https://github.com/rungwiroon/blazorgooglemaps/wiki/Marker-Clustering This C# code demonstrates how to create and cluster markers on a Google Map within a Blazor component. It defines a list of geographical coordinates, creates individual markers for each, and then uses the MarkerClustering class to group them based on proximity. ```csharp private async Task InvokeClustering() { var coordinates = new List() { new LatLngLiteral(147.154312, -31.56391), new LatLngLiteral(150.363181, -33.718234), new LatLngLiteral(150.371124, -33.727111), new LatLngLiteral(151.209834, -33.848588), new LatLngLiteral(151.216968, -33.851702), new LatLngLiteral(150.863657, -34.671264), new LatLngLiteral(148.662905, -35.304724), new LatLngLiteral(175.699196, -36.817685), new LatLngLiteral(175.790222, -36.828611), new LatLngLiteral(145.116667, -37.75), new LatLngLiteral(145.128708, -37.759859), new LatLngLiteral(145.133858, -37.765015), new LatLngLiteral(145.143299, -37.770104), new LatLngLiteral(145.145187, -37.7737), new LatLngLiteral(145.137978, -37.774785), new LatLngLiteral(144.968119, -37.819616), new LatLngLiteral(144.695692, -38.330766), new LatLngLiteral(175.053218, -39.927193), new LatLngLiteral(174.865694, -41.330162), new LatLngLiteral(147.439506, -42.734358), new LatLngLiteral(147.501315, -42.734358), new LatLngLiteral(147.438, -42.735258), new LatLngLiteral(170.463352, -43.999792), }; var result = new List(coordinates.Count()); var index = 1; foreach (var latLngLiteral in coordinates) { var marker = await Marker.CreateAsync(map1.JsRuntime, new MarkerOptions() { Position = latLngLiteral, Map = map1.InteropObject, Label = $"Test {index++}", }); result.Add(marker); } await MarkerClustering.CreateAsync(map1.JsRuntime, map1.InteropObject, result); } ```