html 最小化/优化用于切换Leaflet JS Map中图层的代码

tnkciper  于 2022-12-21  发布在  其他
关注(0)|答案(1)|浏览(98)

我开发了一个显示大量数据集的Map(大约70个不同的层在这一点上)使用传单。切换这些层中的每一个,我使用一个Javascript函数和开关的情况下,添加/删除层的基础上复选框的状态。切换3层,我不得不写6个情况的声明(每层两行代码),对于我的主要项目中的70层,我必须编写140个case语句。尝试了不同的东西,如循环,变量切换和其他人来减少这个代码,但不能破解它只是想知道是否有一个有效的方法来做到这一点。我有意识地对层进行了命名,以使名称与复选框ID以及调用HTML中的函数toggleLayer()时传递的参数相匹配。
下面是我在我的主要项目中所做的一个基本示例。

<!DOCTYPE html>
<html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Simple Example</title>
      <link href="https://fonts.googleapis.com/css2?family=Nunito+Sans:wght@200&display=swap" rel="stylesheet">
      <link rel="stylesheet" 
            href="https://unpkg.com/leaflet@1.8.0/dist/leaflet.css"
            integrity="sha512-hoalWLoI8r4UszCkZ5kL8vayOGVae1oxXe/2A4AO6J9+580uKHDO3JdHb7NzwwzK5xr/Fs0W40kiNHxM9vyTtQ=="
            crossorigin=""/>
      <link rel="stylesheet" href="style.css">    
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  </head>

  <body>
      <main>
          <div class="address-list">
            <p>Use checkboxs to toggle layers</p><br>
            <div class="inputs" id="years">
              <input type="checkbox" id="layer_points_state" onclick='toggleLayer("layer_points_state")' checked="true">States<br>
              <input type="checkbox" id="layer_points_territory" onclick='toggleLayer("layer_points_territory")' checked="true">Territories<br>
              <input type="checkbox" id="layer_polygon" onclick='toggleLayer("layer_polygon")' checked="true">State Polygons
            </div>
          </div>
          <div id="map"></div>
      </main>

      <!-- Leaflet js Packages/libraries -->
      <script src="https://unpkg.com/leaflet@1.8.0/dist/leaflet.js"
              integrity="sha512-BB3hKbKWOc9Ez/TAwyWxNXeoV9c1v6FIeYiBieIWkpLjauysF18NzgR1MBNBXf8/KABdlkX68nAhlwcDFLGPCQ=="
              crossorigin=""></script>
      <script src="./leaflet-providers.js"></script>

      <!-- data files -->
      <script src="state_points.js"></script>
      <script src="state_polygons.js"></script>
      <script src="script.js"></script>

  </body>
</html>

和JS文件

var osmMapHum = L.tileLayer.provider('OpenStreetMap.HOT');
var baseMaps = {'OSM Humanitarian':osmMapHum,}
var map = L.map('map', {
    center: [-26.750867654966356, 136.22808234118338],
    zoom:4.8,
    worldCopyJump: false,
    layers:[osmMapHum]
});

// Start of States Points
function filter_state(feature){
    if (feature.properties.type === 'State')
        return true
}
var layer_points_state = new L.GeoJSON(json_state_point, {filter: filter_state}).addTo(map);
function filter_territory(feature){
  if (feature.properties.type === 'Territory')
      return true
}
var layer_points_territory = new L.GeoJSON(json_state_point, {filter: filter_territory}).addTo(map);
// Start of States Polygon
var layer_polygon = new L.GeoJSON(json_state_polygon, {}).addTo(map);

var overlayMaps = {
                    "States": layer_points_state,
                    "Territories": layer_points_territory,
                    "State Polygon": layer_polygon,
                  };

var layerControl = L.control.layers(baseMaps, overlayMaps, {collapsed:false}).addTo(map);

//toggle layers with checkbox status
function toggleLayer(layer_toggled){
  id_to_check = '#' + layer_toggled
  const cb = document.querySelector(id_to_check);  
  if (cb.checked === true){
      switch (layer_toggled){
                                  case 'layer_points_state': return map.addLayer(layer_points_state);
                                  case 'layer_points_territory': return map.addLayer(layer_points_territory);
                                  case 'layer_polygon': return map.addLayer(layer_polygon);
                            }
  }else{
      switch (layer_toggled){       
                                case 'layer_points_state': return map.removeLayer(layer_points_state);
                                case 'layer_points_territory': return map.removeLayer(layer_points_territory);
                                case 'layer_polygon': return map.removeLayer(layer_polygon);                             
                              }
  }
}

这是Map的外观
How Project looks感谢您的建议

cczfrluj

cczfrluj1#

你可以动态的创建html和逻辑,只需要在layers中添加你想要的过滤器。

var layerContainer = document.getElementById('years');

        var layers = [
            {
                filter: 'State',
                displayName: 'States'
            },
            {
                filter: 'Territory',
                displayName: 'Territories'
            }
        ];

        var overlays = {};

        function prepareFilter(filterType){
            return function(feature) {
                if (feature.properties.type === filterType)
                    return true
            }
        }

        //toggle layers with checkbox status
        function toggleLayer(e){
            var elem = e.target;
            var leafletId = parseInt(elem.id);

            var layerObj = layers.find(x=>x.id === leafletId);

            if(!layerObj){
                console.error('Layer '+leafletId+' not found!');
                return;
            }
            var layer = layerObj.layer;

            if(!elem.checked){
                layer.removeFrom(map);
            } else {
                layer.addTo(map);
            }
        }

        layers.forEach((layerObj)=>{
            var geojsonLayer = new L.GeoJSON(json_state_point, {filter: prepareFilter(layerObj.filter)}).addTo(map);

            // to hide inputs which are not found
            if(geojsonLayer.getLayers().length === 0){
                return;
            }

            overlays[layerObj.filter] = geojsonLayer;
            layerObj.id = L.stamp(geojsonLayer);
            layerObj.layer = geojsonLayer;

            var input = document.createElement('input');
            input.type = 'checkbox';
            input.id = L.stamp(geojsonLayer); //unique leaflet id of the layer
            input.checked = true;
            layerContainer.appendChild(input);

            L.DomEvent.on(input, 'click', toggleLayer);

            var label = document.createElement('label');
            label.innerHTML = layerObj.displayName;
            label.htmlFor = input.id;
            layerContainer.appendChild(label);

            layerContainer.appendChild(document.createElement('br'));
        });

        var layer_polygon = new L.GeoJSON(json_state_polygon, {}).addTo(map);
        overlays["State Polygon"] = layer_polygon;

        var layerControl = L.control.layers({}, overlays, {collapsed:false}).addTo(map);

https://plnkr.co/edit/ddYaazIpSkbZKplC

相关问题