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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With