使用颜色选择器更改图层样式颜色

时间:2017-06-18 19:11:50

标签: javascript jquery openlayers-3

我正在尝试在地图中创建一个工具,以选择我想要应用于特定图层的颜色。 我尝试随机更改颜色,如下面的代码所示:

function getRandomColor() {
        var letters = '0123456789ABCDEF';
        var color = '#';
        for (var i = 0; i < 6; i++ ) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;

    }

var ab =new ol.layer.Vector({
  source: vectorSource,
  style: new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: 'rgba(0, 0, 255, 0.0)',
      width: 0.3
    }),
     fill : new ol.style.Fill({
   color: getRandomColor()
  })
  })
});
var map = new ol.Map({
  layers: [
  new ol.layer.Tile({ source: new ol.source.OSM() }),
  ab
  ],
  target: document.getElementById('mapid'),
  view: new ol.View({
    center: [-1095791.453557, 3422374.879112],
    maxZoom: 19,
    zoom: 5
  })
});

我发现了类似:https://jsfiddle.net/7g7Lh2L2/2/

的内容

但我不知道如何用图层属性替换'#background''background-color'

谢谢;

1 个答案:

答案 0 :(得分:0)

您应该使用fill属性创建样式函数以实现您所需的内容。将为地图图层中的每个对象调用样式函数,您可以检查该要素的属性以确定其fill或调用getRandomColor()函数:

var styleFunction = function() {
  return function(feature,resolution) {
    var style;
    var objProperty = feature.get('<Layer Property Name>'); //Retrieve feature property value
    style = new ol.style.Style({
      image: new ol.style.Circle({
        radius: 10,
        fill: createFillStyle(feature),  //Would call function for each map layer feature to determine fill color
        stroke: createStrokeStyle(feature,resolution) //Example calls function to create stroke for an individual layer feature
      }),
      text: createTextStyle(feature, resolution) //Example calls function to create text style for individual layer feature
    });
    return [style];
  };
};

var ab =new ol.layer.Vector({
  source: vectorSource,
  style: styleFunction()
});

var createFillStyle = function(feature) {
  var fillColor = getRandomColor();
  return new ol.style.Fill({color: fillColor});
}

上面的示例将为地图图层上的每个要素调用getRandomColor()(每个要素在地图图层上的颜色都不同)。如果地图图层上的所有要素只有一种颜色,请在getRandomColor()之前调用var ab =new ol.layer.Vector为地图上的所有地图要素设置一种随机颜色。

搜索openlayers style function以获取更多示例。