【问题标题】:Update polygon leaflet realtime实时更新多边形传单
【发布时间】:2020-01-29 18:56:34
【问题描述】:

我正在尝试显示来自外部 geojson 文件的多边形,数据加载但不实时更新多边形。

添加了多边形,但在级别更改时间隔后颜色不更新。

这是我的代码:

L.realtime({
 url: 'js/areas.json',
 crossOrigin: true,
 type: 'json'
}, {
interval: 60 * 1000,
onEachFeature: function (feature, latlng) {

 var level = feature.properties.level;

 if (level == 0) {

 var polygon = L.polygon(latlng._latlngs, {
   color: '#51F03B',
   opacity: 0.3,
   fillOpacity: 0.1
 }).addTo(map);
} else if (level == 1) {

var polygon = L.polygon(latlng._latlngs, {
  color: '#F43B19',
  opacity: 0.3,
  fillOpacity: 0.1
 }).addTo(map);
}
return polygon;
},
updateFeature: function (feature, oldLayer, newLayer) {

 var level = feature.properties.level;
 if (!oldLayer) {
 return;
 }

 if (level== 0) {
  oldLayer.setStyle({color: '#51F03B'});
 } else if (level == 1) {
  oldLayer.setStyle({color: '#F43B19'});
 }
 return oldLayer;
 }
});

如果我不return oldLayer,多边形颜色会改变,但不要删除之前的多边形。

geoJson 文件:

{
"type": "FeatureCollection",
"features": [{
    "type": "Feature",
    "properties": {
        "level": 0,
        "id": 1
    },
    "geometry": {
        "type": "Polygon",
        "coordinates": [[
            [-75.360297, 6.071571],
            [-76.005083, 6.063846],
            [-76.051694, 6.511708],
            [-75.298149, 6.573451]
        ]]
    }
}]
}

我以这种方式显示标记等,但我不知道多边形是否不同。

【问题讨论】:

    标签: javascript leaflet real-time


    【解决方案1】:

    我对多边形进行“实时”处理的方式是清理前一个多边形并创建一个新多边形。考虑到这一点,您将需要跟踪您创建的层(如在数组中)、清除该层的方法(或清除所有层,有一个 leaflet method for that)和一个设置 timeOut 的方法调用更新方法。

    我说“实时”是因为目前,我一直在使用 timeOut 函数向后端询问更新。

    首先,当您收到 geojson 绘制多边形时,将其添加到您的地图并使用您的更新方法调用 setTimeout。

    其次,您需要一个方法来移除旧层,如下所示:

    const resetPolygonArray = polygonId => { 
        myPolygon = polygonArray.filter(polygon => {
            if (polygon.id != polygonId) {
                return myPolygon
            } else {
            map_machiney.removeLayer(myPolygon.geojson)
            }
        })
    }
    

    即使您可以使用该数组来存储多边形和与其相关的标记,例如以下结构:

    polygonArray.push({
        id: polygonId,
        geojson: geojson,
        marker: marker
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-13
      相关资源
      最近更新 更多