我正在使用Leaflet来实现一些“地图内容”。我将创建一些组,但是我想知道是否可以将圈子应用于layerGroup的每个标记,而不是单独进行。

我知道:

L.circle([-33.519604, -70.596107], 1609.34, {
    color: 'blue',
    fillColor: 'blue'
  }


但是有更好的方法吗?

var L41 = L.marker([-33.431484, -70.584641]).bindPopup('Francisco Bilbao'),
    L42 = L.marker([-33.426224, -70.590973]).bindPopup('Cristóbal Colón'),
    L43 = L.marker([-33.569405, -70.583611]).bindPopup('Elisa Correa');

var L4 = L.layerGroup([L41, L42, L43]);

var mymap = L.map('map', {
  center: [-33.4560406, -70.6681727],
  zoom: 11,
  layers: L4
});

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
  attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
  maxZoom: 18,
  id: 'mapbox.streets',
  accessToken: 'xxxxxxxxx'
}).addTo(mymap);

var linea4 = {
  "Línea 4": L4
}

L.control.layers(null, linea4).addTo(mymap);

最佳答案

LayerGroup有一个getLayers method,该数组返回添加到组中的所有图层的数组。您可以使用该数组为每个标记对象创建一个圆。例如 :

L4.getLayers().forEach(function(obj) {
    if (obj instanceof L.Marker) { // test if the object is a marker
        // get the position of the marker with getLatLng
        // and draw a circle at that position

        L.circle(obj.getLatLng(), 1609.34, {
            color: 'blue',
            fillColor: 'blue'
        }).addTo(map);
    }
});


您还可以使用更简洁的eachLayer,如评论中指出的@ghybs:

L4.eachLayer(function(obj) { ...


和演示



var L41 = L.marker([-33.431484, -70.584641]).bindPopup('Francisco Bilbao'),
    L42 = L.marker([-33.426224, -70.590973]).bindPopup('Cristóbal Colón'),
    L43 = L.marker([-33.569405, -70.583611]).bindPopup('Elisa Correa');

var L4 = L.layerGroup([L41, L42, L43]);

var map = L.map('map', {
  center: [-33.4560406, -70.6681727],
  zoom: 11,
  layers: L4
});
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

L4.getLayers().forEach(function(l) {
    if (l instanceof L.Marker) {
        L.circle(l.getLatLng(), 1609.34, {
            color: 'blue',
            fillColor: 'blue'
        }).addTo(map);
    }
});

html, body {
  height: 100%;
  margin: 0;
}
#map {
  width: 100%;
  height: 100%;
}

<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==" crossorigin=""/>

<script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log==" crossorigin=""></script>

 <div id='map'></div>

09-25 10:10