Leafletjs 将地图动态绑定到可见叠加层

ter*_*esa 1 javascript leaflet

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

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

var group = L.featureGroup(markers); 
map.fitBounds(group.getBounds());
Run Code Online (Sandbox Code Playgroud)

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

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());
Run Code Online (Sandbox Code Playgroud)

iH8*_*iH8 8

您可以使用layeraddlayerremove事件跟踪添加到地图和从地图中删除的图层。每次添加或删除您的特征组之一时,您都需要构建边界。带有注释的工作片段:

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);
Run Code Online (Sandbox Code Playgroud)
body {
    margin: 0;
}

html, body, #leaflet {
    height: 100%;
}
Run Code Online (Sandbox Code Playgroud)
<!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>
Run Code Online (Sandbox Code Playgroud)

希望有帮助,祝你好运。