openlayers2地图控件扩展:要素删除DeleteFeature

实现要素删除控件,扩展OpenLayers.Control类,实现效果:选择DeleteFeature工具后,选择要素,按delete键删除要素(这里的删除只是将feature设置成delete状态,需提交到远程服务器才能删除数据源中的要素),具体代码如下:

 

 1 OpenLayers.Control.DeleteFeature = OpenLayers.Class(OpenLayers.Control.SelectFeature, {
 2     deleteCodes: null,
 3     
 4     /*
 5      * layers--Array[]
 6      * options--Object{}
 7      * */
 8     initialize: function(layers, options) {
 9         var me = this;
10         me.deleteCodes = [46, 68];
11         OpenLayers.Control.SelectFeature.prototype.initialize.apply(this, arguments);
12         me.keyboard = new OpenLayers.Handler.Keyboard(this,{
13             keydown: me.handleKeypress,
14             scope: me
15         });
16     },
17     handleKeypress: function(evt){
18         var code = evt.keyCode;
19         // check for delete key
20         if(OpenLayers.Util.indexOf(this.deleteCodes, code) != -1){
21             var feature = this.handlers.feature.feature;
22             if(!feature)
23                 return;
24             
25             // if feature doesn't have a fid, destroy it
26             if(feature.fid == undefined) {
27                 this.layers[0].destroyFeatures([feature]);
28             } else {
29                 feature.state = OpenLayers.State.DELETE;
30                 this.layers[0].events.triggerEvent("afterfeaturemodified", 
31                         {feature: feature});
32                 this.layers[0].drawFeature(feature);
33             }
34         }
35     },
36     setMap: function(map) {
37         this.keyboard.setMap(map);
38         OpenLayers.Control.SelectFeature.prototype.setMap.apply(this, arguments);
39     },
40     activate: function() {
41         return (this.keyboard.activate() &&
42                 OpenLayers.Control.SelectFeature.prototype.activate.apply(this, arguments));
43     },
44     deactivate: function() {
45         this.keyboard.deactivate();
46         OpenLayers.Control.SelectFeature.prototype.deactivate.apply(this, arguments);
47     },
48     CLASS_NAME: "OpenLayers.Control.DeleteFeature"
49 });

 

效果

 

posted @ 2017-10-20 17:21  GISer-Li  阅读(4315)  评论(0编辑  收藏  举报