首页 > 解决方案 > 是否可以在 Blazor 中使用 Bing 或 Google Maps API?

问题描述

我正在尝试启动并运行地图 API,并努力使 Blazor 与 Js 函数配合得很好。有人有在 Blazor 中工作的 Bing 或 Google 地图的示例,我可以看看吗?

我已经尝试使用 Microsoft 的 Blazor JSInterop 文档中描述的方法引用存储在 wwwroot.index.html 文件中的脚本,但大多只是惨败。

索引.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 "/"
@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");
    }
}

页面加载,但地图没有。

标签: blazor

解决方案


您正在 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>

推荐阅读