【问题标题】:Leafletjs dynamically bound map to visible overlaysLeafletjs 将地图动态绑定到可见覆盖层
【发布时间】:2017-07-28 03:10:03
【问题描述】:

我在我的 Rails 应用程序中使用 Leafletjs,添加标记并将图层组和叠加层用作“类别”。我寻找了有关如何根据可见(“已检查”)叠加层绑定/自动放大和缩小的示例和想法,但找不到太多。

目前,我正在使用一个存储所有地图标记的标记数组,并使用标记数组来绑定地图:

var group = L.featureGroup(markers); 
map.fitBounds(group.getBounds());

但我不确定如何根据地图上的可见覆盖标记动态更新边界。这是我到目前为止所拥有的:

var markers = [];

// a sample of the map markers
var consulting = new L.LayerGroup();
  <% @maps.each do |consulting| %> 
    <% if consulting.category == "Consulting" %>

    markers.push( L.marker( [<%= raw consulting.latitude.to_json %>, <%= raw consulting.longitude.to_json %>]));

    L.marker( [<%= raw consulting.latitude.to_json %>, <%= raw consulting.longitude.to_json %>],  {icon: consultingIcon} )
        .bindPopup( 'hello')
        .addTo(consulting);
    <% end %>
  <% end %> 


var education = new L.LayerGroup();
  <% @maps.each do |education| %> 
    <% if education.category == "Education" %>

      markers.push( L.marker( [<%= raw education.latitude.to_json %>, <%= raw education.longitude.to_json %>]));

      L.marker( [<%= raw education.latitude.to_json %>, <%= raw education.longitude.to_json %>],  {icon: educationIcon} )
        .bindPopup( 'hello')
        .addTo(education);
    <% end %>
  <% end %> 

var mbAttr = '' +
  'Imagery © <a href="http://mapbox.com">Mapbox</a>',
mbUrl = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoidGVyZXNhc2hpaCIsImEiOiJjajU4cWFqNWgwMWgwMnFtazIycTJpbG51In0.4FH-NfH6b44wCc4BFodqWQ';

var grayscale   = L.tileLayer(mbUrl, {id: 'mapbox.light', attribution: mbAttr}),
  streets  = L.tileLayer(mbUrl, {id: 'mapbox.streets',   attribution: mbAttr});

var map = L.map('mapid', {
  center: [43.6532, -79.3832],
  zoom: 5,
  scrollWheelZoom: false,
  layers: [grayscale, consulting, education]
});

var baseLayers = {
  "Grayscale": grayscale,
  "Streets": streets
};

var overlays = {
  "Consulting": consulting,
  "Education": education
};

L.control.layers(baseLayers, overlays).addTo(map);

var group = L.featureGroup(markers); 
map.fitBounds(group.getBounds());

【问题讨论】:

    标签: javascript leaflet


    【解决方案1】:

    您可以使用layeradd 和layerremove 事件跟踪在地图中添加和删除的图层。每次添加或删除其中一个功能组时,您都需要建立界限。与 cmets 一起工作 sn-p 来详细说明:

    var map = new L.Map('leaflet', {
        center: [0, 0],
        zoom: 0,
        layers: [
            new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                'attribution': 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
            })
        ]
    });
    
    map.on('layeradd layerremove', function () {
        // Create new empty bounds
        var bounds = new L.LatLngBounds();
        // Iterate the map's layers
        map.eachLayer(function (layer) {
            // Check if layer is a featuregroup
            if (layer instanceof L.FeatureGroup) {
                // Extend bounds with group's bounds
                bounds.extend(layer.getBounds());
            }
        });
        // Check if bounds are valid (could be empty)
        if (bounds.isValid()) {
            // Valid, fit bounds
            map.fitBounds(bounds);
        } else {
            // Invalid, fit world
            map.fitWorld();
        }
    });
    
    var markers = new L.FeatureGroup([
        new L.Marker([-30, -30]),
        new L.Marker([30, -30]),
        new L.Marker([-30, -60]),
        new L.Marker([30, -60])
    ]).addTo(map);
    
    var polylines = new L.FeatureGroup([
        new L.Polyline([[-30, 30], [30, 60]]),
        new L.Polyline([[30, 30], [-30, 60]])
    ]).addTo(map);
    
    var control = new L.Control.Layers(null, {
        'Markers': markers,
        'Polylines': polylines
    }).addTo(map);
    body {
        margin: 0;
    }
    
    html, body, #leaflet {
        height: 100%;
    }
    <!DOCTYPE html>
    <html>
      <head>
        <title>Leaflet 1.0.3</title>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link type="text/css" rel="stylesheet" href="//unpkg.com/leaflet@1.0.3/dist/leaflet.css" />
      </head>
      <body>
        <div id="leaflet"></div>
        <script type="application/javascript" src="//unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>
      </body>
    </html>

    希望有帮助,祝你好运。

    【讨论】:

    • 使用您的示例,我可以添加FeatureGroups(作为我拥有的类别)并选择它们会动态地将地图缩放到可见标记,但默认情况下它们不会像我以前那样显示。有没有一种方法可以默认显示所有标记,但每次添加或删除FeatureGroups 之一时才重新构建边界?我能够重新添加标记信息窗口,但是当我尝试为所有 FeatureGroups 图层添加 addTo(map) 时,它只会破坏地图。提前谢谢你。
    • 是的,当然,这是可能的。如果在添加图层之前将处理程序附加到地图。我已经编辑了我的示例。
    • 非常感谢,经过一些调整,它可以完美运行。我在边界map.fitBounds(bounds, {padding: [15, 15]}) 添加了一个填充,因为我的标记图标被切断了。我不知道如何添加bindPopup(where text in here came from the "@maps.each" loop),所以我最终将标记存储到一个数组中(带有图标和bindPopup 消息),然后调用var consultingMarkers = new L.FeatureGroup(cMarkers).addTo(map);。
    • 有没有办法添加MarkerCluster?我尝试了var consultingMarkers = new L.markerClusterGroup(cMarkers).addTo(map); 并更新为layer instanceof L.markerClusterGroup,但它破坏了地图。
    【解决方案2】:

    如果我理解正确,您在图层控件中有一些叠加层(consulting 和 education 图层组),并且您希望您的地图在用户切换其中一个叠加层时自动适应可见标记的边界.

    那么困难在于您需要检索可见标记的列表,以便您可以计算它们的边界并相应地调整地图。

    一个简单的解决方案是使用Leaflet.FeatureGroup.SubGroup 插件,这是一个中间“父”功能组,它将获取标记,并用该插件中的子组替换您的类别图层组。这样,当添加到地图时,这些子组实际上会将其子标记添加到父组中。然后,获取所有可见标记的边界变得微不足道:

    var parentGroup = L.featureGroup().addTo(map),
        subGroup1 = L.featureGroup.subGroup(parentGroup),
        subGroup2 = L.featureGroup.subGroup(parentGroup);
    
    // Add your markers into the appropriate SubGroup…
    
    var overlays = {
      'SubGroup 1': subGroup1,
      'SubGroup 2': subGroup2
    };
    
    L.control.layers(null, overlays).addTo(map);
    
    // Have the map adjust view anytime the user uses the Layers Control overlays.
    map.on('overlayadd overlayremove', function () {
      var bounds = parentGroup.getBounds();
    
      // Fit bounds only if the Parent Group actually has some markers,
      // i.e. it returns valid bounds.
      if (bounds.isValid()) {
        map.fitBounds(bounds);
      }
    });
    

    演示:https://jsfiddle.net/3v7hd2vx/354/

    请注意,您不再需要将整个 markers 数组复制到其中。

    免责声明:我是该插件的作者。

    【讨论】:

    • 非常感谢。我一直在寻找添加leaflet.markercluster.js 的方法。但是,我仍然无法获得所有可见标记的范围。我有所有咨询标记到addTo(subGroup1); 和所有教育标记到addTo(subGroup2); 的循环。我将 var parentGroup = L.featureGroup().addTo(map), 更改为 var parentGroup = L.markerClusterGroup().addTo(map), 但它只是破坏了地图。
    • 你应该把它改成一个新问题
    • 我在这里提出了一个新问题:stackoverflow.com/questions/45358983/…。我在哪里使用插件,我到目前为止的代码以及我遇到的问题。我也不确定我是否正确理解了SouthWest 和NorthEast 部分。
    • 至于SouthWest 和NorthEast 的事情,这只是一个检查,以避免试图将地图拟合到空区域的边界。这可以由 iH8 在他的回答中提出的稍微不同的检查 isValid() 代替。为了清楚起见,让我更新上面的答案。
    猜你喜欢
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多