2014-10-07 68 views
1

我试图在使用L.GeoJSON(data).addTo(map)的传单地图上绘制国家/地区形状。然后我要绑定一个弹出该国形状的单击事件...在图层组上打开传单

new L.GeoJSON(data, { 
    onEachFeature: function(feature, layer) { 
    layer['on']('click', popupFunction); 
    } 
}).addTo(this.map); 


popupFunction = function(event) { 
    var layer = event.target; 

    // Open the 'add' popup and get our content node 
    var bound = layer.bindPopup(
    "<div>Hello World!</div>" 
).openPopup(); 

    // Ugly hack to get the HTML content node for the popup 
    // because I need to do things with it 
    var contentNode = $(bound['_popup']['_contentNode']); 
} 

现在,当该数据是一个多边形这工作得很好,因为那时layer属性传递给onEachFeature功能就是这样: 一层。

但是,如果data是一个多面(即美国),这将停止,因为“layer”的工作现在是一个图层组(它有一个_layers)属性,因此没有_popup属性,所以我不能让_contentNode为弹出。

看来这应该是一个相当普遍的事情,希望在layerGroup上弹出。为什么它没有_popup属性?

回答

0

您不能将L.Popup绑定到L.Layer以外的任何其他物件,因为该弹出物将会锚定一些坐标。

对于L.Marker,它将是位置(L.Latlng),对于L.Polygon它将成为中心(请看the code以了解它是如何计算的)。

至于其他情况下(如你),你可以打开一个弹出,但你将不得不决定弹出打开其中:

var popup = L.popup() 
    .setLatLng(latlng) 
    .setContent('<p>Hello world!<br />This is a nice popup.</p>') 
    .openOn(map); 
0

首先,你应该能够在类似的绑定弹出教程Using GeoJSON with Leaflet。类似这样的:

var geoJsonLayer = L.geoJson(data, { 
    onEachFeature: function(feature, layer) { 
    layer.bindPopup('<div>Hello World!</div>'); 
    } 
}).addTo(map); 

如何进一步处理您的popUps取决于您的用例。这也许能为你够:

geoJsonLayer.eachLayer(function(layer) { 
    var popUp = layer._popup; 
    // process popUp, maybe with popUp.setContent("something"); 
}); 

希望这有助于..

1

简短的回答:图层组不支持弹出

B计划:

你应该考虑使用FeatureGroup,它扩展LayerGroup并具有bindPopup方法,这是一个示例

L.featureGroup([marker1, marker2, polyline]) 
 
    .bindPopup('Hello world!') 
 
    .on('click', function() { alert('Clicked on a group!'); }) 
 
    .addTo(map);

+0

如果这解决了您的问题,请将其设置为正确答案 – 2016-12-21 11:43:01