使用传单和geoJson监控对象

Monitoring the objects using leaflet and geoJson

本文关键字:geoJson 监控 对象      更新时间:2023-09-26

任务是:

根据现有地理数据(一组纬度/经度值)在地图上显示对象(标记)。地理数据会定期更新,所以这就像是对地图上物体的一种交互式监控

我正在使用传单框架来达到目标。此外,我使用geoJson来输出geoData(具有lat/long坐标的对象)。这是我的代码:

// for a start make it as a template
var geoData = {
  "type": "FeatureCollection",
  "features": []
};
// add a feature, assign an id and properties
function addFeature(id, latitude, longitude, properties) {
  // first of all check if the feature have already exists
  var index = IndexOfItem(id);
  if (index >= 0) {
    // if exists then update only coordinates and properties
    geoData.features[index].geometry.coordinates = [longitude, latitude];
    geoData.features[index].properties.popupContent = properties;
  } else {
    // add new feature
    var feature = {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [longitude, latitude]
      },
      "properties": {
        "popupContent": properties
      },
      "id": id
    };
    geoData.features.push(feature);
  }
}
// search and return the index of feature if exists
function IndexOfItem(id) {
  for (var i = 0; i < geoData.features.length; i++) {
    if (id == geoData.features[i].id) {
      return i;
    }
  };
  return -1;
}

这段代码运行良好。之后,我添加了一个由这些特征组成的新层,当阵列更新时(一些特征会更改坐标),我必须从地图中删除该层,并创建一个新的L.geoJson(geoData)对象。该过程一次又一次地重复,同时特征的坐标也会更新。

事实上,我不擅长JavaScript,只有这样我才能解决任务。但在我看来,这就像一个硬编码,可能有一些JavaScript方法可以更优雅地解决这个问题。有人能给我一个建议(或想法),如何做得更好,甚至获得更多的表现吗?我将非常感谢任何帮助!

您只需要使用L.layerGroup并从该集合中添加和移除即可进行管理。也许还可以使用数据绑定框架来缓存地图视图,这样它就可以实时更改,而不必刷新。