index.html

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

        }
    </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("initGoogleMap", new { Lat = this.Store.Lat, Lng = this.Store.Lng });
            }
        }

Adding Marker

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

    <script>
        function initGoogleMap(obj) {

            var myLatlng = new google.maps.LatLng(obj.lat, obj.lng);

            var mapOptions = {
                zoom: 18,
                center: myLatlng
            }
            var map = new google.maps.Map(document.getElementById("map"), mapOptions);

            var marker = new google.maps.Marker({
                position: myLatlng,
                title: obj.title
            });

            // To add the marker to the map, call setMap();
            marker.setMap(map);

        }
    </script>

Sources:

https://www.syncfusion.com/faq/blazor/general/how-can-i-add-google-maps-to-a-blazor-application

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

Last modified: March 8, 2021

Author

Comments

Write a Reply or Comment