leafletjs – marker.bindPopup – 保持所有弹出窗口打开

我在使用传单打开所有弹出窗口时遇到一些困难。

我在循环中有以下代码将标记添加到LayerGroup(ajax自动更新)。

var marker = L.marker([value.position.lat, value.position.lon],options).addTo(markers); allpoints.push([value.position.lat, value.position.lon]); marker.bindPopup("InfoWindow",{closeOnClick:false,closeButton:false}).openPopup(); 

它工作得很好,除了它只保持最后一个弹出窗口打开。 我想保持所有这些都开放。 我确实在这里找到了一篇关于使用不同标记名称的文章(stackoverflow),但是我在循环中有这个。 我确实尝试将L.marker放入一个数组中,但传单并不喜欢这样。

有任何想法吗?

您需要覆盖Leaflet Map上的openpopup方法,将其替换为此方法的副本,仅注释掉调用this.closePopup()的行;

在您的页面上,您将添加

 L.Map = L.Map.extend({ openPopup: function (popup, latlng, options) { if (!(popup instanceof L.Popup)) { var content = popup; popup = new L.Popup(options).setContent(content); } if (latlng) { popup.setLatLng(latlng); } if (this.hasLayer(popup)) { return this; } // NOTE THIS LINE : COMMENTING OUT THE CLOSEPOPUP CALL //this.closePopup(); this._popup = popup; return this.addLayer(popup); } }); 

http://jsfiddle.net/yVLJf/37/

你可以在这里找到原始的Leaflet openPopup方法: https : //github.com/Leaflet/Leaflet/blob/1acffc5a3d31010b7d613382ab2a5830ecee5dd5/src/layer/Popup.js#L290

如果要一次渲染所有弹出窗口,则可以将弹出窗口渲染为单独的图层。 你不能在marker.bindPopup(Popup)之后使用marker.openPopup(),因为Leaflet在打开的当前关闭其他弹出窗口。

我的React应用程序中有相同的任务。

例如this.api = L.map(this.map);

 drawMarkers() { const {points, keepAllPopupsOpen} = this.props; this.markers.clearLayers(); points.forEach(point => { const hasPopup = point.title; const marker = this.createMarker(point, keepAllPopupsOpen); this.markers.addLayer(marker); if (hasPopup) { const popup = this.createPopup(point, keepAllPopupsOpen); if (keepAllPopupsOpen) { this.api.addLayer(popup); } else { marker.bindPopup(popup); } } }); } 

使用禁用的参数可以在弹出窗口中禁用关闭按钮,并防止在弹出窗口外单击关闭弹出窗口:

 createPopup(point, disabled = false) { const {title, location} = point; const popup = L.popup({ closeOnClick: !disabled, closeButton: !disabled, offset: [-22, -38] }) .setLatLng(location) .setContent(title); return popup; }