在OpenLayers集群功能中更改样式

时间:2019-03-22 19:30:43

标签: json mapping openlayers openlayers-3

我正在将OpenLayers与Javascript结合使用,并在地图上显示群集特征。我想根据其属性值之一更改群集内功能的图标。

var style1 = new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
        anchor: [0.5, 66],anchorXUnits: 'fraction',anchorYUnits: 'pixels',
        opacity: 0.85,src: 'https://img.icons8.com/flat_round/64/000000/home.png',scale: 0.3
      }));
      var style2 = new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
        anchor: [0.5, 66],anchorXUnits: 'fraction',anchorYUnits: 'pixels',
        opacity: 0.85,src: 'https://img.icons8.com/color/48/000000/summer.png',scale: 0.3
      }));
      function myStyleFunction(feature) {
        let props = feature.getProperties();
        if (props.id>50) {
          console.log(props.id);
          return new ol.style.Style({image: style1,stroke: new ol.style.Stroke({ color:"#fff", width:1 }) });
        } else {
          console.log(props.id);
          return new ol.style.Style({image: style2,stroke: new ol.style.Stroke({ color:"#fff", width:1 }) });
        }
      };

在上面的代码中,我想访问群集中某个功能的属性“ id”,并根据“ id”值设置其图标。但是,我无法获得feature属性。

这里是codepen。我会感谢任何人的帮助。

1 个答案:

答案 0 :(得分:1)

如果仅检查每个群集中的第一个功能:

  function myStyleFunction(feature) {
    let props = feature.get('features')[0].getProperties();
    if (props.id>50) {
      console.log(props.id);
      return new ol.style.Style({image: style1,stroke: new ol.style.Stroke({ color:"#fff", width:1 }) });
    } else {
      console.log(props.id);
      return new ol.style.Style({image: style2,stroke: new ol.style.Stroke({ color:"#fff", width:1 }) });
    }
  };

如果要在群集中的任何功能中查找值

  function myStyleFunction(feature) {
    let maxId = 0;
    feature.get('features').forEach(function(feature){
      maxId = Math.max(maxId, feature.getProperties().id);
    });
    if (maxId>50) {
      console.log(maxId);
      return new ol.style.Style({image: style1,stroke: new ol.style.Stroke({ color:"#fff", width:1 }) });
    } else {
      console.log(maxId);
      return new ol.style.Style({image: style2,stroke: new ol.style.Stroke({ color:"#fff", width:1 }) });
    }
  };

对于ol-ext集群

  function myStyleFunction(feature) {
    let id = 0;
    let features = feature.get('features');
    if (features) {
      id = features[0].get('id');
    }
    if (id > 50) {
      return new ol.style.Style({image: style1,stroke: new ol.style.Stroke({ color:"#fff", width:1 }) });
    } else {
      return new ol.style.Style({image: style2,stroke: new ol.style.Stroke({ color:"#fff", width:1 }) });
    }
  };