如果您正在刷新具有控件的地图,请注意不要有多个控件和事件处理程序(请参阅本文末尾的最后一条说明)。
两个不同的事件可以关闭您的弹出窗口:弹出窗口内的 CLOSE ('X') 框和在弹出窗口失去焦点时关闭弹出窗口的自动过程。
这个伪代码取自一个功能图,当用户点击任何 MARKER 时,弹出窗口就会出现。
我在地图上创建了一个图层(在这种情况下,来自动态 KML 文件,由 php 解析):
var urlKML = 'parseKMLTrack07d.php';
var layerKML = new OpenLayers.Layer.Vector("KML1", {
strategies: [new OpenLayers.Strategy.Fixed()],
protocol: new OpenLayers.Protocol.HTTP({
url: urlKML,
format: new OpenLayers.Format.KML({
extractStyles: true,
extractAttributes: true,
maxDepth: 2
})
})
});
然后我创建一个选择控件,我称之为“selectStop”,并将 2 个函数关联到事件(当标记被选中和取消选中时):
var selectStop = new OpenLayers.Control.SelectFeature(layerKML,{onSelect: onFeatureSelect, onUnselect: onFeatureUnselect});
layerKML.events.on({
"featureselected": onFeatureSelect,
"featureunselected": onFeatureUnselect
});
map.addControl(selectStop);
selectStop.activate();
这是选择或取消选择标记时的两个功能
function onFeatureSelect(event) {
var feature = event.feature;
var content = feature.attributes.name + '<br/>'+feature.attributes.description;
popup = new OpenLayers.Popup.FramedCloud("chicken",
feature.geometry.getBounds().getCenterLonLat(),
new OpenLayers.Size(100,100),
content,
null, true, onFeatureUnselect);
feature.popup = popup;
map.addPopup(popup);
// GLOBAL variable, in case popup is destroyed by clicking CLOSE box
lastfeature = feature;
}
function onFeatureUnselect(event) {
var feature = lastfeature;
if(feature.popup) {
map.removePopup(feature.popup);
feature.popup.destroy();
delete feature.popup;
}
}
请注意,在 onFeatureSelect 函数中,我创建了一个名为“lastfeature”的全局变量。我这样做的原因是我的 onFeatureUnselect 将用于销毁弹出窗口,以防它被取消选择或关闭框被点击。
如果我没有将该功能保存为全局变量,我将不得不分别处理取消选择和关闭框单击,因为导致每个事件的事件不同。
为了在弹出窗口中创建关闭框,我将倒数第二个参数(在 onFeatureSelect 函数的弹出窗口声明中)设置为 TRUE,并将 onFeatureUnselect 命名为关闭框的回调函数:
popup = new OpenLayers.Popup.FramedCloud("chicken",
feature.geometry.getBounds().getCenterLonLat(),
new OpenLayers.Size(100,100),
content,
null, true, onFeatureUnselect);
最后注意:如果您在层上使用刷新,请注意不要重复您的处理程序。在这种情况下,当您的 javascript 启动时,创建一个变量“id1”,它将保存您的 selectStop 控件 ID。在创建新的控件和处理程序之前检查它是否存在。像这样:
if (id1 == '') {
var selectStop = new OpenLayers.Control.SelectFeature(layerKML,{onSelect: onFeatureSelect, onUnselect: onFeatureUnselect});
layerKML.events.on({
"featureselected": onFeatureSelect,
"featureunselected": onFeatureUnselect
});
map.addControl(selectStop);
selectStop.activate();
id1 = selectStop.id;
} else {
selectStop = OpenLayers.Control.SelectFeature(layerKML,{onSelect: onFeatureSelect, onUnselect: onFeatureUnselect});
}
您可以通过在 onFeatureSelect 中添加警报来检查是否复制了事件处理程序。如果您单击一个标记并获得多个警报窗口,那么您有重复的处理程序。您会得到无法销毁弹出窗口的印象,这是不正确的。您销毁了一个弹出窗口,但您有 N 个相同的弹出窗口(顺便说一下,具有相同的 id)。