Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Bing or Google Maps APIs in Blazor?

Tags:

blazor

I'm trying to get a map API up and running and struggling to make Blazor play nice with Js functions. Has anybody got an example of Bing or Google maps working in Blazor I could take a look at?

I've tried referencing the script stored in the wwwroot.index.html file using the methods described in Microsoft's Blazor JSInterop documentation, but have mostly just failed miserably.

index.html:

<body>
    <app>Loading...</app>
    <script type='text/javascript'>
        function loadMapScenario() {
            var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {});
            var pushpin = new Microsoft.Maps.Pushpin(map.getCenter(), null);
            map.entities.push(pushpin);
            return "";
        }
    </script>
    <script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?key=###&callback=loadMapScenario' async defer></script>
    <script src="_framework/blazor.webassembly.js"></script>
</body>

blazor page:

@page "/"
@inject IJSRuntime JSRuntime

<h1>Hello, world!</h1>

Welcome to your new app.

<div id='myMap' style='width: 400px; height: 300px;'></div>

@functions {
    protected override async Task OnInitAsync()
    {
        var text = await JSRuntime.InvokeAsync<string>("loadMapScenario");
    }
}

The page loads, but the map does not.

like image 946
Nakovi49 Avatar asked May 02 '19 18:05

Nakovi49


1 Answers

You are calling the map script in the OnInitAsync method but the page has not yet been rendered at this point. Try calling it in the OnAfterRenderAsync method once the page has been rendered.

protected override async Task OnAfterRenderAsync()
{
    var text = await JSRuntime.InvokeAsync<string>("loadMapScenario");
}

also reorder your javascript includes

  <script src="_framework/blazor.webassembly.js"></script>

  <script type='text/javascript'>

    function loadMapScenario() {
        debugger;
        var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {});
        var pushpin = new Microsoft.Maps.Pushpin(map.getCenter(), null);
        map.entities.push(pushpin);
        return "";
    }

</script>


<script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?key=###&callback=loadMapScenario' async defer></script>
like image 109
Laurence73 Avatar answered Oct 10 '22 18:10

Laurence73