Leaflet.js动态将地图绑定到可见的叠加层 [英] Leafletjs dynamically bound map to visible overlays

查看:87
本文介绍了Leaflet.js动态将地图绑定到可见的叠加层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的Rails应用程序中使用leafletjs,添加标记并将图层组和叠加层用作类别".我寻找了一些示例和想法,说明如何基于可见(选中")的叠加层进行绑定/自动缩放,但找不到太多.

I am using leafletjs in my Rails app, adding the markers and using layer groups and overlays as "categories". I looked for examples and ideas on how I could bound/auto-zoom in and out based on the visible ("checked") overlays but couldn't find much.

当前,我使用的是可存储所有地图标记的markers数组,并使用markers数组绑定地图:

Currently, I'm using a markers array that stores all the map markers and using the markers array to bound the map:

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

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

But I'm not sure how to dynamically update the bounds based on the visible overlay markers on the map. This is what I have so far:

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());

推荐答案

您可以使用layeraddlayerremove事件来跟踪在地图上添加或删除的图层.每当添加或删除一个要素组时,您都需要构建边界.带有注释的工作片段,以进行详细说明:

You can keep track of layers being added to and removed from the map using the layeradd and layerremove events. You'll need to build the bounds everytime one of your featuregroups gets added or removed. Working snippet with comments to elaborate:

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>

希望如此,祝您好运.

这篇关于Leaflet.js动态将地图绑定到可见的叠加层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆