关于javascript:OpenLayers使用相同的vectorSource添加圆形特征会增加所有对象的不透明度

OpenLayers adding circle feature with same vectorSource increases opacity of all

背景

规格

  • OpenLayers 4.4.1
  • OSM

我是OpenLayers的新手,以前从未使用过向量(主要是因为我发现我正在使用OpenLayers版本1,并且不得不重新学习所有内容)。

我的应用程序在地图上添加了与位置相关的圆圈,并带有指示位置精度的特定半径。

在操作中,多个圆会在不同时间添加到地图。

这是我加载地图的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var map = new ol.Map({
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      })
    ],
    target: 'mapdiv',
    controls: ol.control.defaults({
      attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
        collapsible: false
      })
    }),
    view: new ol.View({
      //center: [0, 0],
      zoom: 16
    })
  });

  //this is where all map 'features' (circles) are stored
  var vectorSource = new ol.source.Vector({
   projection: 'EPSG:4326'
  });

如您所见,我了解到,只要您将其指定为"源",就可以在地图后立即加载"矢量源",因为我知道它包含所有在地图上显示的"矢量"。

这是我用来生成圆(源)的代码(我在getPointResolution处对其进行了调整,因为OP出错了):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  //code from https://stackoverflow.com/a/28299599
  function addCircle(map, vectorSource, radius) {
    var view = map.getView();
    var projection = view.getProjection();
    var resolutionAtEquator = view.getResolution();
    var center = view.getCenter();
    var pointResolution = ol.proj.getPointResolution(projection, resolutionAtEquator, center);
    var resolutionFactor = resolutionAtEquator/pointResolution;
    var radius = (radius / ol.proj.METERS_PER_UNIT.m) * resolutionFactor;


    var circle = new ol.geom.Circle(center, radius);
    var circleFeature = new ol.Feature(circle);

    // vector layer
    vectorSource.addFeature(circleFeature);
    var vectorLayer = new ol.layer.Vector({
     source: vectorSource
    });

    map.addLayer(vectorLayer);
  }

问题

正常加载一个圆,会在指定位置以指定半径添加一个蓝色描边的不透明圆。

加载第二个圆圈比上一个更加不透明。将地图移动到上一个圆,它也更加不透明。

每添加一个圆圈,所有显示的圆圈的表观不透明度都会增加。

example

在每个生成的圆中运行vectorLayer.getOpacity()都会导致1,这显然是半透明的,在每个新圆中变得越来越不透明。

概要

环顾四周,似乎经常出现这样的情况:开发人员一遍又一遍地重新加载同一个圆,直到许多堆叠在一起。对我来说几乎也是如此,除了我三遍检查了我只运行了addCircle()一次并且圆与上一个不同的位置之外。

OpenLayers是否有可能在每个新圈子中重画所有以前的圈子?

也许这与getOpacity无关,但是与color作为rgba()组合有关...

我希望每个圆在绘制新圆后都保持不变。默认的不透明度和颜色很好。

我做错什么了吗?

这里有个小提琴-https://jsfiddle.net/f5zrLt20/5/


定义vectorSource时定义图层:

1
2
3
4
5
6
var layer = null;

//this is where all map 'features' (circles) are stored
var vectorSource = new ol.source.Vector({
  projection: 'EPSG:4326'
});

并检查是否在创建新圈子时存在:

1
2
3
4
5
6
7
8
9
10
11
12
// If layer is not yet set, create new layer and add it to map
if (!layer) {
  vectorSource.addFeature(circleFeature);
  layer = new ol.layer.Vector({
    source: vectorSource
  });
  map.addLayer(layer);
}
//Otherwise, just add feature to the source
else {
  layer.getSource().addFeature(circleFeature);
}