Steps:

  1. Create Google Cloud account.
  2. Enable “Maps Javascript API”.
  3. Create API key.
  4. Add code and key to app.

Example:

index.html


    <script async
            src="https://maps.googleapis.com/maps/api/js?key=<your_api_key>&callback=initMap">
    </script>
    <script>
        function initMap() {
            map = new google.maps.Map(document.getElementById("map"), {
                center: { lat: -34.397, lng: 150.644 },
                zoom: 8,
            });
        }
    </script>

mypage.razor

<div id="map" style="height:500px;width:100%;"></div>

mypagebase.cs

using Microsoft.JSInterop;

        [Inject]
        public IJSRuntime jsRuntime { get; set; }

        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {              
                await jsRuntime.InvokeVoidAsync("initMap");
                StateHasChanged();
            }
        }

Sources:

https://developers.google.com/maps/gmp-get-started

https://console.cloud.google.com/projectselector2/google/maps-apis/overview

https://developers.google.com/maps/documentation/javascript/overview

https://stackoverflow.com/questions/59524910/launch-google-maps-on-blazor

Last modified: March 7, 2021

Author

Comments

Write a Reply or Comment