从对象数组中创建数组的纯JavaScript方法

3
var cityMarkers = [
    {
        id: "bliss",
        name: "Principality of Bliss",
        icon: cityIcon,
        coords: [-90.19, -76.90]
    },
    {
        id: "cantonia",
        name: "Grand City of Cantonia",
        icon: cityIcon,
        coords: [-39.513421, -69.09375]
    },
    {
        id: "mithril",
        name: "Grand City of Mithril ",
        icon: cityIcon,
        coords: [42, -102.5]
    }];

我将上述内容放在一个单独的文件中,以便从我的app.js文件中引用。

  cityMarkers.forEach(function(item) {
      var marker = L.marker(item.coords, {icon : item.icon});
      marker.bindTooltip("<b>" + item.name + "<b>", {permanent: true, offset: 
  [60, 0]});

这将创建标记和其他属性,但不会将它们放在地图上。一个数组可以处理将它们放在地图上,所以这对我真正想做的事情没有帮助。
这是基于leaflet库的地图。我正在尝试为每个城市分配一个带有id的变量。然后,在标记被制作并附加到它们的变量之后,我想将那些名称制作成数组以用作数据层。我承认我在这方面很菜。任何指导都将不胜感激。如果有人需要,我在下面链接了文档。

https://leafletjs.com/reference-1.3.4.html

我已经研究了这个问题,但是没有找到任何能回答我所问的问题的结果。我更希望得到一点指引而不是直接的答案。我不明白如何实例化变量并将它们绑定到标记。感谢您的时间。
2个回答

2

不要直接将标记添加到地图上,而是添加到L.layerGroup中。您可以将layerGroup添加到地图上,随时再次删除。

var lg = new L.layerGroup();
cityMarkers.forEach(function(item) {
      var marker = L.marker(item.coords, {icon : item.icon});
      marker.bindTooltip("<b>" + item.name + "<b>", {permanent: true, offset: 
  [60, 0]})
  .addTo(lg)});

lg.addTo(map);       // Add the layerGroup the map
lg.removeFrom(map);  // Remove the layerGroup from the map

嗯,这个可行。但我有点困惑。我原本以为不会成功,因为数组值没有唯一的变量。我认为这在引用层以包含在我的控制中以切换所有城市时很重要。所以,我的真正问题是:当从循环中创建数组值时,它们是如何分配的?顺便感谢你的回答! - Decipher Me Please

0

我认为你可以尝试添加.addTo(map)

cityMarkers.forEach(function(item) {
  var marker = L.marker(item.coords, {icon : item.icon});
  marker
    .bindTooltip("<b>" + item.name + "<b>", {permanent: true, offset: [60, 0]})
    .addTo(map);

在leaflet中添加多个标记的演示。


是的,它会将它们添加到地图中,但它们不会在启用切换的图层中。 - Decipher Me Please
参数 permanent true 使它们停留在地图上。 你能检查一下这个吗 https://jsfiddle.net/3v7hd2vx/2875/ - Shyam
参数 permanent 是一个工具提示选项。它使文本永久显示,而不是标记。 - Decipher Me Please
为了清晰起见,permanent 和 offset 是选项对象的一部分,该对象是 bindToolTip() 方法的一部分。无论如何,感谢您抽出时间作出回应。 - Decipher Me Please

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接