Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Launch Google Maps On Blazor

I am trying to launch Google maps on my Server side Blazor app using JSInterop. I seem to have tried just about everything but can't get the map to show. Unfortunately there is very little samples if any about it on the internet since it's a fairly new framework and I am equally just getting my feet wet on Blazor myself, so I am probably doing a whole lot of things wrong. Any nudge in the right direction would be appreciated.

In my component file, I have:

@page "/MapTest"
@inject IJSRuntime JSRuntime

<style>
    #map {
        width: 60%;
        height: 60%;
    }
</style>

<h1>Display Google Map</h1>


<div @ref="map" id="map"></div>

@code {

    ElementReference map; // reference to the DIV

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await JSRuntime.InvokeVoidAsync("Showgooglemap", null);
        //StateHasChanged();

    }
}

On my _Host.cshtml file, I have:

   <script src="_framework/blazor.server.js"></script>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=xxxmykeyxxx&v=3"></script>

    <script type="text/javascript">
            function initialize() {
                var latlng = new google.maps.LatLng(40.716948, -74.003563);
                var options = {
                    zoom: 14, center: latlng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                var map = new google.maps.Map(document.getElementById
                    ("map"), options);
        }
            //google.maps.event.addDomListener(window, 'load', initialize);

//i tried wrapping the call in a function to see if it helps
        function Showgooglemap() {
            google.maps.event.addDomListener(window, 'load', initialize);
        }
      </script>
like image 763
flylily Avatar asked Dec 30 '19 02:12

flylily


2 Answers

You can use the package BlazorGoogleMaps from rungwiroon as well. It supports

  • Map
  • Marker
  • Symbols
  • InfoWindow
  • Polygon, LineString, Rectangle, Circle
  • Routes
  • Coordinates
  • Bounds
  • Styles

and is available on Github and NuGet.

I'm using it and it works really well.

like image 165
FranzHuber23 Avatar answered Sep 22 '22 17:09

FranzHuber23


You can use this Nuget package. It will give your Blazor app full control over Google Static and JavaScript Maps API as well. Usage can be complicated so recommend to read the documentation for more details and check the demo app.

enter image description here

Other Nuget package can help you access Browsers Geolocation services as well. See Geo JS docs as well as demo app.

like image 32
Major Avatar answered Sep 19 '22 17:09

Major