如何在OpenLayers中创建自定义几何?

时间:2019-03-17 00:41:27

标签: openlayers openlayers-5

我正在使用OpenLayers v5向地图添加一些绘图工具。一旦完成此任务需要文档或开箱即用之外的自定义图形:同心圆。

我真的不知道从哪里开始,所以我有两个问题。

我可以以某种方式创建单个几何并将geometryFunction用作demonstrated in the examples,还是我需要创建多个特征,每个圆圈一个?

Geometry作为独立创建以便与OpenLayers一起使用时到底需要什么? X,Y坐标的集合?

为了尝试自己解决这个问题,使用文档中的绘图示例,我尝试从对象中获取坐标,然后重新创建它,并将其手动添加到源中,如下所示; < / p>

const feature = new Feature({
  geometry: new Circle(
    [
      /**
       * These are the nubmers that come out of a native Circle drawing
       * when console.log'ing the feature.getGeomety.getFlatCoordinates().
       * No idea if this is how I'd get or set those values.
       */
      [-10448062.740758311, 4941309.912009362],
      [ -9953141.960354999, 4941309.912009362],
    ]
  )
});

source.addFeature(feature);

这不会出错,但是无法显示圆圈。

1 个答案:

答案 0 :(得分:3)

当交互类型为“圆”时,坐标将包含两对[x,y]圆心和当前点。这足以计算半径和旋转。几何必须是单个简单的几何,因此需要将同心圆转换为多多边形。

 // OpenLayers default drawing style doesn't include stroke for MultiPolygon

 var white = [255, 255, 255, 1];
 var blue = [0, 153, 255, 1];
 var width = 3;
 styles = [
   new ol.style.Style({
 fill: new ol.style.Fill({
   color: [255, 255, 255, 0.5]
 })
   }),
   new ol.style.Style({
 stroke: new ol.style.Stroke({
   color: white,
   width: width + 2
 })
   }),
   new ol.style.Style({
 stroke: new ol.style.Stroke({
   color: blue,
   width: width
 })
   }),
   new ol.style.Style({
 image: new ol.style.Circle({
   radius: width * 2,
   fill: new ol.style.Fill({
     color: blue
   }),
   stroke: new ol.style.Stroke({
     color: white,
     width: width / 2
   })
 }),
 zIndex: Infinity
   })
 ];

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

  var source = new ol.source.Vector({wrapX: false});

  var vector = new ol.layer.Vector({
    source: source,
  });

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

  var typeSelect = document.getElementById('type');

  var draw; // global so we can remove it later
  function addInteraction() {
    var value = typeSelect.value;
    if (value !== 'None') {
      var geometryFunction;
      if (value === 'Square') {
        value = 'Circle';
        geometryFunction = ol.interaction.Draw.createRegularPolygon(4);
      } else if (value === 'Box') {
        value = 'Circle';
        geometryFunction = ol.interaction.Draw.createBox();
      } else if (value === 'Star') {
        value = 'Circle';
        geometryFunction = function(coordinates, geometry) {
          var center = coordinates[0];
          var last = coordinates[1];
          var dx = center[0] - last[0];
          var dy = center[1] - last[1];
          var radius = Math.sqrt(dx * dx + dy * dy);
          var rotation = Math.atan2(dy, dx);
          var newCoordinates = [];
          var numPoints = 12;
          for (var i = 0; i < numPoints; ++i) {
            var angle = rotation + i * 2 * Math.PI / numPoints;
            var fraction = i % 2 === 0 ? 1 : 0.5;
            var offsetX = radius * fraction * Math.cos(angle);
            var offsetY = radius * fraction * Math.sin(angle);
            newCoordinates.push([center[0] + offsetX, center[1] + offsetY]);
          }
          newCoordinates.push(newCoordinates[0].slice());
          if (!geometry) {
            geometry = new ol.geom.Polygon([newCoordinates]);
          } else {
            geometry.setCoordinates([newCoordinates]);
          }
          return geometry;
        };
      } else if (value === 'Concentric') {
        value = 'Circle';
        geometryFunction = function(coordinates, geometry) {
          var center = coordinates[0];
          var last = coordinates[1];
          var dx = center[0] - last[0];
          var dy = center[1] - last[1];
          var radius = Math.sqrt(dx * dx + dy * dy);
          var rotation = Math.atan2(dy, dx);
          var newCoordinates = [];
          var numCircles = 3;
          for (var i = numCircles; i > 0; --i) {
            var circle = new ol.geom.Circle(center, radius * i/numCircles);
            newCoordinates.push(ol.geom.Polygon.fromCircle(circle, 64, rotation).getCoordinates());
          }
          if (!geometry) {
            geometry = new ol.geom.MultiPolygon(newCoordinates);
          } else {
            geometry.setCoordinates(newCoordinates);
          }
          return geometry;
        };
      }
      draw = new ol.interaction.Draw({
        source: source,
        type: value,
        geometryFunction: geometryFunction,
        style: styles
      });
      draw.on('drawend', function(evt){
        if (evt.feature.getGeometry().getType() == 'MultiPolygon') {
          var polygons = evt.feature.getGeometry().getPolygons();
          for (var i = 0; i < polygons.length; ++i) {
            center = ol.extent.getCenter(polygons[i].getExtent());
            radius = ol.extent.getWidth(polygons[i].getExtent())/2;
            if (i == 0) {
              evt.feature.setGeometry(new ol.geom.Circle(center, radius));
            } else {
              source.addFeature(new ol.Feature(new ol.geom.Circle(center, radius)));
            }
          }
        }
      });
      var modify = new ol.interaction.Modify({source: source});
      map.addInteraction(modify);
      map.addInteraction(draw);
    }
  }


  /**
   * Handle change event.
   */
  typeSelect.onchange = function() {
    map.removeInteraction(draw);
    addInteraction();
  };

  addInteraction();
html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
}
.map {
    width: 100%;
    height: 80%;
}
<link href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" rel="stylesheet" />
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<div id="map" class="map"></div>
<form class="form-inline">
  <label>Shape type &nbsp;</label>
  <select id="type">
    <option value="Circle">Circle</option>
    <option value="Square">Square</option>
    <option value="Box">Box</option>
    <option value="Star">Star</option>
    <option value="Concentric">Concentric</option>
    <option value="None">None</option>
  </select>
</form>

相关问题