Issue with Duplicating Icons on Google Maps Buttons in Blazor .NET8 Application
I’m encountering a recurring issue in my Blazor .NET8 application where the buttons on my Google Maps (such as the zoom and fullscreen buttons) display repeated icons every time I navigate away from the map page and then return to it. Initially, when the map loads for the first time, everything appears normal. However, upon returning to the map after visiting other parts of the application, the icons on the map controls multiply.
Desired Behavior
I want the icons on the Google Maps buttons to remain singular and not duplicate when navigating away from and back to the map page.
Specific Problem
Each time I navigate back to the map page, the icons on the map controls (zoom, fullscreen, etc.) duplicate.
Code Example
Here is a simplified version of my code to illustrate the problem:
@page "/map"
@* MapContainer.razor *@
<div id="map" style="height: 400px;"></div>
@code {
private IJSRuntime _jsRuntime;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await _jsRuntime.InvokeVoidAsync("initializeMap");
}
}
}
@* JavaScript code *@
<script>
let map;
function initializeMap() {
if (!map) {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8
});
}
}
function cleanupMap() {
if (map) {
google.maps.event.clearInstanceListeners(map);
map = null;
}
}
window.addEventListener('beforeunload', cleanupMap);
</script>
Request for Help
Could anyone suggest why this might be happening and how to fix this issue or properly clean up or reset the Google Maps instance to prevent icons from duplicating on the controls? Any insights or suggestions would be greatly appreciated!
Thank you in advance for your help!
Steps Taken
- Ensuring that the Google Maps API script is loaded only once.
- Cleaning up the map instance using JavaScript before reinitializing the map.
- Removing all markers, event listeners, and resetting the map variable to null.
TomW22 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.