如何在鼠标悬停时通过超链接在 leaflet.js 中显示突出显示的轮廓?

How do you make a highlighted outline appear in leaflet.js on mouseover and by hyperlink?

当用户将鼠标悬停在传单中的对象上时,我需要在对象周围显示一个轮廓。现在,我可以使对象始终突出显示或根本不突出显示。这是我的代码示例:

var polygon1 = L.polygon([
  [83.34425, -19.51172], 
  [83.2571, -15.86426], 
  [83.07408, -16.04004], 
  [82.78192, -17.31445], 
  [82.62569, -11.42578], 
  [82.36164, -11.29395], 
  [82.11236, -12.48047], 
  [82.37332, -22.71973], 
  [82.64822, -22.93945], 
  [83.34425, -19.51172]
], {
  color: 'yellow',
  opacity: 0.0,
  fillColor: '#fff',
  fillOpacity: 0.0
});
polygon1.bindLabel(popup_csb);
polygon1.bindPopup(content_csb);
polygon1.addTo(map);

我需要在两种情况下为要概述的对象创建一个事件。

  1. 鼠标悬停时,显示突出显示以及弹出标签。当鼠标离开对象时,突出显示就会消失。

  2. 当用户单击页面(建筑物列表)上的 link 并且对象被勾勒出轮廓以向用户显示建筑物在地图上的位置时。

第二种情况也必须在用户单击另一个建筑物时有一个禁用事件。

非常感谢您的帮助!

首先,您需要准备好默认样式和突出显示样式:

var style = {
    'default': {
        'color': 'yellow'
    },
    'highlight': {
        'color': 'red'
    }
};

创建一些多边形并将它们分组以便于访问:

var group = new L.LayerGroup([
    new L.Polygon([
        [-50, -50], [50, -50], [50, -10], [-50, -10]
    ], {
        'label': 'Polygon 1',
        'popup': 'Polygon 1'
    }),
    new L.Polygon([
        [-50, 10], [50, 10], [50, 50], [-50, 50]
    ], {
        'label': 'Polygon 2',
        'popup': 'Polygon 2'
    })
]).addTo(map);

创建一个变量来存储高亮层和设置和取消设置高亮的函数:

// Variable for storing highlighted layer
var highlight;

function setHighlight (layer) {
  // Check if something's highlighted, if so unset highlight
  if (highlight) {
    unsetHighlight(highlight);
  }
  // Set highlight style on layer and store to variable
  layer.setStyle(style.highlight);
  highlight = layer;
}

function unsetHighlight (layer) {
  // Set default style and clear variable
  layer.setStyle(style.default);
  highlight = null;
}

遍历图层、设置样式、绑定标签和弹出窗口并添加处理程序:

// Iterate
group.eachLayer(function (layer) {

    // Set default style
    layer.setStyle(style.default);
    // Bind label with polygon option variable
    layer.bindLabel(layer.options.label);
    // Bind popup with polygon option variable
    layer.bindPopup(layer.options.popup);

    // Mouseover handler
    layer.on('mouseover', function (e) {
        // Set highlight
        setHighlight(layer);
    });

    // Mouseout handler
    layer.on('mouseout', function (e) {
         // Unset highlight
        unsetHighlight(layer);
    });

    // Fetch list from DOM
    var list = L.DomUtil.get('list'),
        // Add list item
        item = L.DomUtil.create('li', 'item', list),
        // Add link
        link = L.DomUtil.create('a', 'link', item);

    // Set link text
    link.textContent = layer.options.label;
    // Set link href
    link.href = '#';

    // Add clickhandler to link
    L.DomEvent.addListener(link, 'click', function (e) {
        // Set highlight
        setHighlight(layer);
    });
});

示例:http://plnkr.co/edit/LjzFbI?p=preview