Openlayers - 不同几何类型的多种样式

Meh*_*way 2 openlayers-3

所以我使用一个矢量图层来放置我的所有内容:

  • 积分
  • 折线
  • 多边形

这是我的代码:

var source = new ol.source.Vector({ wrapX: false });
var vector = new ol.layer.Vector({
    source: source,
    style: // styleFunction or style or [style] don't know...
});
Run Code Online (Sandbox Code Playgroud)

我想根据他们的类型来设计功能。我在文档中找到了这个,但不知道如何使用它:

...单独的编辑样式具有以下默认值:

 styles[ol.geom.GeometryType.POLYGON] = [
   new ol.style.Style({
     fill: new ol.style.Fill({
       color: [255, 255, 255, 0.5]
     })
   })
 ];
 styles[ol.geom.GeometryType.LINE_STRING] = [
   ...
 ];
 styles[ol.geom.GeometryType.POINT] = [
   ...
 ];
Run Code Online (Sandbox Code Playgroud)

有任何想法吗 ?

pav*_*los 6

查看官方拖放示例 --> ol3 示例

它涉及所有可能的几何形状。

所以,声明你的样式对象

    var defaultStyle = {
    'Point': new ol.style.Style({
      image: new ol.style.Circle({
        fill: new ol.style.Fill({
          color: 'rgba(255,255,0,0.5)'
        }),
        radius: 5,
        stroke: new ol.style.Stroke({
          color: '#ff0',
          width: 1
        })
      })
    }),
    'LineString': new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: '#f00',
        width: 3
      })
    }),
    'Polygon': new ol.style.Style({
      fill: new ol.style.Fill({
        color: 'rgba(0,255,255,0.5)'
      }),
      stroke: new ol.style.Stroke({
        color: '#0ff',
        width: 1
      })
    }),
    'MultiPoint': new ol.style.Style({
      image: new ol.style.Circle({
        fill: new ol.style.Fill({
          color: 'rgba(255,0,255,0.5)'
        }),
        radius: 5,
        stroke: new ol.style.Stroke({
          color: '#f0f',
          width: 1
        })
      })
    }),
    'MultiLineString': new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: '#0f0',
        width: 3
      })
    }),
    'MultiPolygon': new ol.style.Style({
      fill: new ol.style.Fill({
        color: 'rgba(0,0,255,0.5)'
      }),
      stroke: new ol.style.Stroke({
        color: '#00f',
        width: 1
      })
    })
  };
Run Code Online (Sandbox Code Playgroud)

然后创建您的样式函数

var styleFunction = function(feature, resolution) {
    var featureStyleFunction = feature.getStyleFunction();
    if (featureStyleFunction) {
      return featureStyleFunction.call(feature, resolution);
    } else {
      return defaultStyle[feature.getGeometry().getType()];
    }
  };
Run Code Online (Sandbox Code Playgroud)

最后,将样式函数分配给矢量图层

    map.addLayer(new ol.layer.Vector({
      source: new ol.source.Vector({}),
      style: styleFunction
    }));
Run Code Online (Sandbox Code Playgroud)