OpenLayers-Vector图层上添加Feature

调用Vector Layer的addFeatures方法可以在Vector Layer上添加新Feature

1. 定义WKT Geometry

var wkt  = "POLYGON((0 0,0 90,180 90,180 0,0 0))”;

2. 创建Vector图层

var vlayer = new OpenLayers.Layer.Vector("Vector Layer");
map.addLayer(vlayer);

3. 创建Geometry

var wkt_c = new OpenLayers.Format.WKT();
var geometry = wkt_c.read(wkt);

4.将geometry添加到vlayer上

vlayer.addFeatures(geometry);

完整代码

复制代码
 1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
 2 <HTML>
 3  <HEAD>
 4   <TITLE> OpenLayers : Add Feature </TITLE>
 5   <link rel="stylesheet" href="./OpenLayers-2.10/theme/default/style.css" type="text/css" />
 6   <link rel="stylesheet" href="./css/style.css" type="text/css" />
 7   <script src="./OpenLayers-2.10/lib/OpenLayers.js"></script>
 8   <script  type="text/javascript">
 9     
10     var wms_url = "http://192.168.111.156:8080/geoserver/wms?";
11     var wms_version = "1.3.0";
12 
13     var vlayer = null;
14 
15     function init()
16     {
17         //创建map对象,
18         map = new OpenLayers.Map("map");
19         var layer = new OpenLayers.Layer.WMS("OpenLayers WMS",
20                                              wms_url,
21                                              {layers: 'country'},
22                                              {singleTile: true});
23 
24         // 创建Vector图层
25         vlayer = new OpenLayers.Layer.Vector("Vector Layer");
26 
27         // 添加图层
28         map.addLayers([layer,vlayer]);
29         map.addControl(new OpenLayers.Control.LayerSwitcher());
30 
31         map.zoomToMaxExtent();
32     }
33 
34     function onAddFeatureClick()
35     {
36         // 获取输入WKT
37         var geomt = document.getElementById("geomtext");
38         var wkt = geomt.value;
39 
40         // 由WKT转换为geometry对象
41         var wkt_parser = new OpenLayers.Format.WKT();
42         var geometry = wkt_parser.read(wkt);
43         // 将geometry添加到图层上
44         vlayer.addFeatures(geometry);
45     }
46   </script>
47 
48  </HEAD>
49 
50  <BODY onload="init()">
51   <div>
52         <div><input type="button" value="addFeature(WKT)" onClick="onAddFeatureClick();"></div>
53       <!--POINT(0 0)-->
54       <!--LINESTRING((-180 -90,180 90))-->
55       <!--POLYGON((0 0,0 90,180 90,180 0,0 0))-->
56       <div><textarea type="text" id="geomtext" rows="5"

转载自:https://blog.csdn.net/xiaohan2826/article/details/49510213

You may also like...