在OpenLayers集群功能中更改样式

问题描述 投票:0回答:1

我正在使用带有Javascript的OpenLayers并在地图上显示群集功能。我想根据其属性值之一更改群集中功能的图标。

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”值设置其图标。但是,我无法获得功能属性。

这是一个codepen。我很感激任何人的帮助。

json mapping openlayers openlayers-3
1个回答
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 }) });
    }
  };
© www.soinside.com 2019 - 2024. All rights reserved.