OpenLayers的selector工具相信挺多人都沒有用過,其實這個工具用處還是不少的。比如完成元素查詢時,需要實現圖屬性聯動,使用這個工具很方便。最近做項目時也使用到這個工具,使用起來確實挺方便的。效果如圖:
紅色部分為使用selector選擇的效果。
下面說說實現過程:
定義selector工具,並添加到地圖中
//高亮元素選擇 selectControls = { selector: new OpenLayers.Control.SelectFeature(this.hightLightVectorLayer, { selectStyle: { fillColor: 'red', zIndex: 500 }, toggle: true, onSelect: function (feature) { that.hightLineEleSelectCallback(feature, that); }, onUnselect: function (feature) { that.map.popups.length > 0 && that.map.popups[0].destroy(); } }) }; map.addControl(selectControls['selector']]);
這里要和大家說說它的幾個屬性:
(1)this.hightLightVectorLayer指的是目標圖層,這個工具可以選擇哪個圖層上的元素。
(2)selectStyle:{},是選中元素的樣式。
(3)Toggle是指第一個點擊選中上,第二次取消選中,第三次選中…..
(4)onSelect是一個事件類型的屬性,指選中元素后,執行的操作,有個參數feature,feture有該元素的fid等信息,可以用來進行圖屬聯動
(5)onUnselect指的是圖層中非元素的點擊事件。
(6)還有其他的許多屬性,如hover: false,callback等,有興趣的可以看看。
2.元素選擇回調方法。主要是添加pupop到地圖上顯示信息。也可使用feature.attributes.fid屬性和屬性結果進行聯動。我這里做的是添加popup到地圖上,代碼如下:
/* * 岩石地層高亮元素選擇回調方法,展示popup * Parameters: * feature: - {Openlayers feature element} 當前選中的元素 * that: - {object} 當前上下文 */ hightLineEleSelectCallback: function (feature, that) { //添加popup內容 var popupStr = '<div class="faultInfoPopupCon">' '<div class="head rockHead">' returnData.name '<label>123</label></div>' '<div class="rockMain">' '<table>' '<tr>' '<td><label class="name">厚度:</label></td>' '<td><label class="value">123m</label></td>' '</tr>' '<tr>' '<td><label class="name">岩性描述:</label></td>' '<td><label class="value">mayday</label></td>' '</tr>' '</table>' '</div>' '</div>'; //add popup feature.popup = new OpenLayers.Popup.NestFramedCloud("pop", feature.geometry.getBounds().getCenterLonLat(), null, popupStr, null, true, function () { //pupop關閉方法 selectControls.selector.unselectAll(); map.popups.length > 0 &&map.popups[0].destroy(); }, { imageSrc: baseUrl 'Scripts/libs/rrpopup/img/nest-popup.png' }); map.popups.length > 0 && map.popups[0].destroy(); map.addPopup(feature.popup); },
關於這個OpenLayers.Control.SelectFeature工具,還有其他很多的屬性,大家可以參考類OpenLayers.Control.SelectFeature進行學習。