我正在尝试使用JSInterop在服务器端Blazor应用程序上启动Google地图。我似乎已经尝试了几乎所有内容,但无法显示地图。不幸的是,由于它是一个相当新的框架,因此在Internet上几乎没有样本,因为我只是在自己接触Blazor时,所以我可能做错了很多事情。任何朝着正确方向的推动都会受到赞赏。
在我的组件文件中,我有:
@page "/MapTest"
@inject IJSRuntime JSRuntime
<style>
#map {
width: 60%;
height: 60%;
}
</style>
<h1>Display Google Map</h1>
<div @ref="map" id="map"></div>
@code {
ElementReference map; // reference to the DIV
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await JSRuntime.InvokeVoidAsync("Showgooglemap", null);
//StateHasChanged();
}
}
在_Host.cshtml文件中,我具有:
<script src="_framework/blazor.server.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=xxxmykeyxxx&v=3"></script>
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(40.716948, -74.003563);
var options = {
zoom: 14, center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById
("map"), options);
}
//google.maps.event.addDomListener(window, 'load', initialize);
//i tried wrapping the call in a function to see if it helps
function Showgooglemap() {
google.maps.event.addDomListener(window, 'load', initialize);
}
</script>
欢迎@flylily,您快完成了。我在示例Blazor-server-side
项目中运行您的代码。我只改变两件事。一个是从百分比像素(高度变化的百分比高度HTML 5)和另一种是调用initialize
的函数insteedShowgooglemap
具有因initialize
功能上已经初始化地图page load
或first render
。完整的代码如下,尝试使用这些代码...
_Host.cshtml文件,
<script src="_framework/blazor.server.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key={{put-your-api-key}}&v=3"></script>
<script>
function initialize() {
var latlng = new google.maps.LatLng(40.716948, -74.003563);
var options = {
zoom: 14, center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById
("map"), options);
}
</script>
MapTest.razor组件,
@page "/MapTest"
@inject IJSRuntime JSRuntime
<h1>Display Google Map</h1>
<div id="map" style="height:500px;width:100%;">
</div>
@code{
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JSRuntime.InvokeVoidAsync("initialize", null);
StateHasChanged();
}
}
}
最后,运行您的应用程序并享受。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句