jquery 通过变量动态获取对象数组的数据

igetnqfo  于 2022-11-29  发布在  jQuery
关注(0)|答案(1)|浏览(219)

我的Map使用leaflet
我添加了以下标记:

var markers = [];
var markerOne = L.circleMarker([000000,000000],{icon: MyIcon, alt:"M1"}).addTo(map);
    markers.push(markerOne);
var markerTwo = L.circleMarker([000000,000000],{icon: MyIcon, alt:"M2"}).addTo(map);
    markers.push(markerTwo);
var markerThree = L.circleMarker([000000,000000],{icon: MyIcon, alt:"M3"}).addTo(map);
    markers.push(markerThree);
var markerFour = L.circleMarker([000000,000000],{icon: MyIcon, alt:"M4"}).addTo(map);
    markers.push(markerFour);
// aso.

所有工作正常。现在我想动态分组一些标记
1 -“静态”方式有效:

var markerGroup1 = [markerOne, markerThree];
 var MyMarkerGroup = L.layerGroup(markerGroup1); // set of markers

2 -但我所有的尝试都以动态方式失败:

var markerGroup1 = "markerOne, markerThree"; // As info: I got this names dynamically by a function
 markerGroup1 = MyMarkers.split(","); // To get them as array
 var MyMarkerGroup = L.layerGroup(markerGroup1); // set of markers

在开发控制台中,我发现在第二个例子中,“标记名称的对象数据”将不会被捕获。为什么?

wz3gfoph

wz3gfoph1#

那是因为
L.layerGroup([markerOne, markerThree])是一个标记数组,
L.layerGroup(["markerOne", "markerThree"])是字符串数组
这样就行了

var markers = {
  "markerOne": L.circleMarker([000000,000000],{icon: MyIcon, alt:"M1"}).addTo(map),
  "markerTwo": L.circleMarker([000000,000000],{icon: MyIcon, alt:"M2"}).addTo(map),
  "markerThree": L.circleMarker([000000,000000],{icon: MyIcon, alt:"M3"}).addTo(map),
  "markerFour": L.circleMarker([000000,000000],{icon: MyIcon, alt:"M4"}).addTo(map)
};

var group1 = "markerOne, markerThree".split(", ");  // add the space or have no spaces!
var markerGroup1= group1.map(markerName => markers[markerName])
var MyMarkerGroup = L.layerGroup(markerGroup1); // set of markers

相关问题