openlayers学习笔记

五章-54-绘制要素并修改

2020-04-07  本文已影响0人  彩云飘过

本文基于腾讯课堂老胡的课《跟我学Openlayers--基础实例详解》做的学习笔记,使用的openlayers 5.3.x api。

源码 见 1054.html ,对应的 官网示例
https://openlayers.org/en/latest/examples/draw-and-modify-features.html?q=geometry

https://openlayers.org/en/latest/examples/modify-features.html?q=modi

https://openlayers.org/en/latest/examples/snap.html?q=modi

image.png image.png
<!DOCTYPE html>
<html>

<head>
   <title>绘制要素并修改</title>
   <link rel="stylesheet" href="../include/ol.css" type="text/css" />
   <script src="../include/ol.js"></script>
</head>
<style></style>

<body>
   <form class="form-inline">
       <label>几何类型 &nbsp;</label>
       <select id="type">
           <option value="Point">点</option>
           <option value="LineString">线</option>
           <option value="Polygon">多边形</option>
           <option value="Circle">圆</option>
       </select>
   </form>

   <div id="map" class="map"></div>

   <script>
       var raster = new ol.layer.Tile({
           source: new ol.source.OSM()
       });

       var source = new ol.source.Vector();
       var vector = new ol.layer.Vector({
           source: source,
           style: new ol.style.Style({
               fill: new ol.style.Fill({
                   color: 'rgba(255, 255, 255, 0.2)'
               }),
               stroke: new ol.style.Stroke({
                   color: '#ffcc33',
                   width: 2
               }),
               image: new ol.style.Circle({
                   radius: 7,
                   fill: new ol.style.Fill({
                       color: '#ffcc33'
                   })
               })
           })
       });

       var map = new ol.Map({
           layers: [raster, vector],
           target: 'map',
           view: new ol.View({
               center: [-11000000, 4600000],
               zoom: 4
           })
       });

       var modify = new ol.interaction.Modify({ 
           source: source,
           insertVertexCondition: function (){return true} //来控制是否添加新的顶点,
            });
       map.addInteraction(modify);

       var draw, snap; 
       var typeSelect = document.getElementById('type');

       function addInteractions() {
           draw = new ol.interaction.Draw({
               source: source,
               type: typeSelect.value
           });
           map.addInteraction(draw);

           //增加吸附操作,当吸附在要素之后,可以修改要素
           snap = new ol.interaction.Snap({ source: source });
           map.addInteraction(snap);
       }

       
       typeSelect.onchange = function () {
           //删除 绘制 和吸附的交互,再重新添加绘制 和吸附操作
           map.removeInteraction(draw);
           map.removeInteraction(snap);
           addInteractions();
       };

       addInteractions();
   </script>
</body>

</html> 
上一篇 下一篇

猜你喜欢

热点阅读