You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Thingsboard自定义Widget中通过JS绘制地图线条?

在ThingsBoard自定义Widget地图里画线条的实现方法

要在自定义地图Widget里画线,核心是利用TbMapWidgetV2底层的Leaflet地图库API,直接调用Leaflet的L.polyline方法就能实现。

代码调整细节:

  • 坐标数组的放置:
    如果是固定线路,把lineCoordinates放在onInit里就行;如果要根据设备数据动态更新线路,就把坐标逻辑移到onDataUpdated函数里。

  • 初始化线条:
    在onInit里创建线条实例并添加到地图上,同时把线条对象存在self.ctx里,方便后续更新或销毁。

  • 动态更新(可选):
    要是需要根据设备上报的坐标改线路,在onDataUpdated里用setLatLngs方法更新线条坐标即可。

完整修改后的代码:

self.onInit = function() {
    // 初始化地图
    self.ctx.map = new TbMapWidgetV2('openstreet-map', false, self.ctx);
    
    // 定义线路坐标(固定线路放这里)
    var lineCoordinates = [
        { lat: 37.774929, lng: -122.419418 },  // 起点
        { lat: 37.804996, lng: -122.407547 }   // 终点
    ];
    
    // 创建线条并添加到地图,可自定义样式
    self.ctx.polyline = L.polyline(lineCoordinates, {
        color: 'red',
        weight: 3,
        opacity: 0.7
    }).addTo(self.ctx.map.map);
}

self.onDataUpdated = function() {
    // 动态更新线路示例:从数据点中获取新坐标
    // var newCoords = self.ctx.dataPoints.map(p => ({ lat: p.lat, lng: p.lng }));
    // self.ctx.polyline.setLatLngs(newCoords);
    
    self.ctx.map.update();
}

self.onResize = function() {
    self.ctx.map.resize();
}

self.actionSources = function() {
    return TbMapWidgetV2.actionSources();
}

self.onDestroy = function() {
    // 销毁线条,避免内存泄漏
    if (self.ctx.polyline) {
        self.ctx.map.map.removeLayer(self.ctx.polyline);
    }
    self.ctx.map.destroy();
}

self.typeParameters = function() {
    return {
        hasDataPageLink: true
    };
}

注意点:

  • self.ctx.map.map是TbMapWidgetV2暴露的Leaflet原生地图实例,所有Leaflet的API都能直接用。
  • 销毁Widget时一定要移除线条图层,不然会有内存泄漏问题。

内容的提问来源于stack exchange,提问作者Bevin NIno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 21:30:22