如果您正在刷新具有控件的地圖,請注意不要有多個控件和事件處理程序(請參閱本帖最後的最後一個註釋)。
兩個不同的事件可以關閉您的彈出窗口:彈出窗口內的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」和I 2層的功能相關聯事件(當選擇了MARKER和未選定):
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'的GLOBAL變量。我這樣做的原因是,我的onFeatureUnselect將被用於銷燬彈出窗口,以防它被取消選擇或CLOSE BOX被點擊。
如果我沒有將該功能保存爲全局變量,我將不得不分別處理取消選擇和關閉框,因爲導致每個事件的事件都不相同。
創建彈出內部的關閉框,我設置了倒數第二個參數(在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 puting警報。如果你點擊一個標記並獲得多個警報窗口,那麼你有重複的處理程序。你會覺得你不能銷燬一個彈出窗口,這是不真實的。你銷燬了一個彈出窗口,但是你有N個相同的彈出窗口(順便說一下,使用相同的ID)。