Search code examples
blazormauiblazor-jsinterop

Calling Method from JS Dotnet Maui Blazor App


Hello All, I can implement google map into Maui Blazor app. with following codes: How to retrieve strCoord to OnCenterChanged Method from JS function. Please help...

I added following codes to index.html:

<script async src="https://maps.googleapis.com/maps/api/js?key=API_KEY"></script>
<script src="js/googleMapsInterop.js" type="text/javascript"></script>

googleMapsInterop.js

function initialize() {
    var latlng = new google.maps.LatLng(39.925533, 32.866287);
    var options = {
        zoom: 8, center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map"), options);

    map.addListener("center_changed", function () {
        var center = map.getCenter();

        var latitude = center.lat();
        var longitude = center.lng();
        
        var strCoord = latitude.toString() + "," + longitude.toString();

       //I NEED TO GET strCoord TO "onCenterChaned" Method in Blazor Component. 

      console.log("Current center coordinates: " + latitude + ", " + longitude);
    });


    window.addPin = function (map) {
        var center = map.getCenter();
        var marker = new google.maps.Marker({
            position: center,
            map: map,
            title: "Title Here"
        });
    };
}

GoogleMap.razor

@inject IJSRuntime _JsRuntime


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

@code {
       
   protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await _JsRuntime.InvokeVoidAsync("initialize", null);
        }
    }
  [JSInvokable]
  public static void OnCenterChanged(string strCoord)
  {
  // ...
  }
 }

Thanks for your collaboration!


Solution

  • For this, you can check the official document: Call .NET methods from JavaScript functions in ASP.NET Core Blazor.

    This article explains how to invoke .NET methods from JavaScript (JS).

    To invoke a static .NET method from JavaScript (JS), use the JS functions:

    -DotNet.invokeMethodAsync (recommended): Asynchronous for both server-side and client-side components.

    -DotNet.invokeMethod: Synchronous for client-side components only.

    Pass in the name of the assembly containing the method, the identifier of the static .NET method, and any arguments.