我对Web编程非常陌生,因此由于来自WPF / C#背景,所以我发现Blazor具有吸引力。但是,我试图启动并运行地图API,并努力使Blazor与Js函数配合使用。我可以看看有人在Blazor中使用Bing或Google地图的例子吗?或者,如果我接近我的代码,告诉我我是个白痴吗?
我曾尝试使用Microsoft Blazor JSInterop文档中描述的方法来引用存储在wwwroot.index.html文件中的脚本,但是大多数情况下不幸地失败了。
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>
辉煌页面:
@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");
}
}
页面加载,但地图未加载。
答案 0 :(得分:1)
您正在使用OnInitAsync方法调用地图脚本,但此时页面尚未呈现。呈现页面后,尝试在OnAfterRenderAsync方法中调用它。
protected override async Task OnAfterRenderAsync()
{
var text = await JSRuntime.InvokeAsync<string>("loadMapScenario");
}
还要重新排序您的javascript包括
<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>