如何将具有特定 class 的标记添加到图层或图层组?

How to add a marker with a specific class to a layer or layergroup?

我有几个带有 css class 名称的标记,例如:markerOne 的 .markerone 为 css class,等等. 可以创建一个函数来将这些标记分配给特定的图层或组吗?像 var layerone = $(L.marker).hasClass("markerone")); 之类的东西并在层内分配所有带有 class 的标记? 我想这样做,以便稍后我可以使用 addLayer 和 removeLayer 切换该层 on/off。

我用来显示标记的函数:

function showResourcesByName(name) {
            for (var i = 0; i < markers.resources.length; i++) {
                var resName = markers.resources[i].name;

                if (resName == name) {
                    var resIcon = icons.resources[i].icon;
                    var resSize = icons.resources[i].size;
                    var resPname = icons.resources[i].pname;

                    var customIcon = L.icon({
                        iconUrl: resIcon,
                        iconSize: resSize, // size of the icon
                        iconAnchor:   [resSize[0]/2, resSize[1]/2], // point of the icon which will correspond to marker's location
                        popupAnchor:  [2, -resSize[1]/2] // point from which the popup should open relative to the iconAnchor
                    });

                    for (var j = 0; j < markers.resources[i].coords.length; j++) {
                        var x = markers.resources[i].coords[j].x;
                        var y = markers.resources[i].coords[j].y;

                        marker = L.marker([y, x], {icon: customIcon});
                        marker.addTo(map).bindPopup(resPname);
                        $(marker._icon).addClass(name)



                    }
                }
            }
        }

我说的class是$(marker._icon).addClass(name)中的(name)部分,从markers.js:[=14=中抓取name ]

    var markers = {
  "resources": [
    {
      "name": "AITokarServer",
      "coords": [
        {
          "x": -1210.0,
          "y": -1770.0
        },
        {
          "x": -1230.0,
          "y": -1810.0
        },

所以所有名为 AITokarServer 的标记都将有一个 class .AITokarServer 等等。

在Leaflet中,标记没有CSS 类。标记有图标,图标有 className 选项,所以:

var marker1 = L.marker({ 
      icon: L.icon({ 
             className: 'green'
             // Other icon options
      })
      // Other marker options
 });

console.log(marker1.options.icon.options.className);

您可以通过创建自定义标记 class 向 L.Marker 添加一些功能,使事情变得更容易。连接到 onAdd 函数,以便您可以在标记初始化时自动分配一个 class 名称。您可以添加一个函数来检查 classname:

L.CustomMarker = L.Marker.extend({

    // Overwrite onAdd function
    onAdd: function (map) {

        // Run original onAdd function
        L.Marker.prototype.onAdd.call(this, map);

        // Check if there's a class set in options
        if (this.options.className) {

            // Apply className to icon and shadow
            L.DomUtil.addClass(this._icon, this.options.className);
            L.DomUtil.addClass(this._shadow, this.options.className);
        }

        // return instance
        return this;
    },

    // Function for checking class
    hasClass: function (name) {

        // Check if a class is set in options and compare to given one
        return this.options.className && this.options.className === name;
    }
});

现在您可以在标记初始化时轻松应用 class名称:

var marker = new L.CustomMarker([0, 0], {
    'className': 'foobar'
}).addTo(map);

然后检查你的标记上是否设置了某个 class:

if (marker.hasClass('foobar')) {
    // YES! Do stuff
}

也就是说,您实际上不需要向标记添加 classes 以将它们分成不同的组。您的数据结构中已经有这些组。考虑以下结构:

var markers = [{
    'name': 'Foo',
    'coordinates': [{
        'lat': -25,
        'lng': -25
    }, {
        'lat': 25,
        'lng': -25
    }]
}, {
    'name': 'Bar',
    'coordinates': [{
        'lat': -25,
        'lng': 25
    }, {
        'lat': 25,
        'lng': 25
    }]
}];

要将它们放入不同的组,首先创建一个对象来存储您稍后可以添加到图层控件的组:

var overlays = {};

现在您可以迭代结构,为每组标记创建图层组并将它们添加到其中:

// iterate the structure, handle each group
markers.forEach(function (group) {

    // check if there's already a group for this name
    if (!overlays.hasOwnProperty(group.name)) {

        // new group, create layergroup, store in object and add to map
        overlays[group.name] = new L.LayerGroup().addTo(map);
    }

    // iterate the coordinates for this group
    group.coordinates.forEach(function (coordinate) {

        // create markers for each coordinate and add to the layergroup
        new L.Marker([coordinate.lat, coordinate.lng]).addTo(overlays[group.name]);

    })
});

现在您可以将覆盖对象添加到图层控件,以便切换它们:

new L.Control.Layers(null, overlays).addTo(map);

这是一个关于 Plunker 的工作示例:http://plnkr.co/edit/t0YiJO8RmEdnIKKXugdm?p=preview

如果需要,您仍然可以添加 class 名称,方法是使用上面的自定义标记 class 并像这样更改坐标迭代器:

group.coordinates.forEach(function (coordinate) {
    new L.CustomMarker([coordinate.lat, coordinate.lng], {
        'className': group.name
    }).addTo(overlays[group.name]);
})

这是一个关于 Plunker 的工作示例:http://plnkr.co/edit/cHPSLKDbltxr9jFZotOD?p=preview