Blazor WASM调用searoute-js库遇阻,求正确实现方案
解决Blazor .NET 7 WASM集成searoute-js生成海运航线的问题
1. 修正JS模块的导入与函数实现
调整wwwroot/scripts/searoute.js代码,确保正确导入searoute-js并适配坐标参数顺序(searoute要求坐标格式为[经度, 纬度]):
// 导入searoute-js的编译文件,适配浏览器环境 import searoute from '../lib/searoute-js/searoute.min.js'; export async function calculateWayPoints(lat1, lon1, lat2, lon2, resolution) { try { // 转换坐标顺序为[lon, lat]传入searoute const route = await searoute({ start: [lon1, lat1], end: [lon2, lat2], resolution: resolution }); // 提取航线坐标并转换为Blazor可接收的格式 const waypoints = route.geometry.coordinates.map(coord => ({ Latitude: coord[1], Longitude: coord[0] })); console.log('生成的海运航线点:', waypoints); return waypoints; } catch (error) { console.error('计算海运航线出错:', error); throw error; // 抛出错误让Blazor捕获 } }
2. 配置项目拷贝searoute-js资源到wwwroot
Blazor WASM不会自动包含node_modules文件,在项目的.csproj中添加拷贝任务,将searoute的编译文件复制到发布目录:
<Target Name="CopySearouteAssets" AfterTargets="Build"> <Copy SourceFiles="$(SolutionDir)node_modules/searoute-js/dist/searoute.min.js" DestinationFolder="$(TargetDir)wwwroot/lib/searoute-js" /> </Target>
3. 调整Blazor代码处理返回值与错误
修改组件代码,改用InvokeAsync获取航线点,添加错误捕获与资源释放逻辑:
@inject IJSRuntime js @implements IAsyncDisposable private IJSObjectReference? _seaRouteModule; protected override async Task OnAfterRenderAsync(bool firstRender) { await base.OnAfterRenderAsync(firstRender); if (firstRender) { try { _seaRouteModule = await js.InvokeAsync<IJSObjectReference>("import", "./scripts/searoute.js"); // 参数顺序:起点纬度、起点经度、终点纬度、终点经度、分辨率 var seaRoutePoints = await _seaRouteModule.InvokeAsync<List<MapCoordinate>>("calculateWayPoints", 43.3, 5.3, 31.2, 121, 8); // 将生成的航线点更新到Syncfusion Map控件 UpdateMapNavigationRoute(seaRoutePoints); } catch (Exception ex) { Console.WriteLine($"加载海运航线模块失败: {ex.Message}"); } } } // 定义接收JS返回坐标的模型类 public class MapCoordinate { public double Latitude { get; set; } public double Longitude { get; set; } } private void UpdateMapNavigationRoute(List<MapCoordinate> routePoints) { // 此处编写更新Syncfusion Map航线的逻辑 // 示例:替换地图导航线的数据源 // NavigationRouteData = routePoints.Select(p => new MapRoutePoint(p.Latitude, p.Longitude)).ToList(); // StateHasChanged(); } // 释放JS模块资源 public async ValueTask DisposeAsync() { if (_seaRouteModule != null) { await _seaRouteModule.DisposeAsync(); } }
4. 常见问题排查
- 坐标顺序错误:searoute-js要求坐标为
[经度, 纬度],务必在JS中转换传入的参数顺序,否则会生成错误航线。 - 模块加载404:检查浏览器控制台的网络请求,确认
searoute.min.js和自定义JS文件的路径是否正确。 - 运行时错误:打开浏览器F12控制台查看具体错误信息,常见原因包括模块导出不兼容、参数类型错误等。
内容的提问来源于stack exchange,提问作者user21415940
相关产品推荐
相关产品推荐

