Access default OpenLayers style
Asked Answered
G

3

6

I have a ol.StyleFunction set on a layer.

function style(feature: ol.Feature, resolution: number): ol.style.Style {
  return ol.style.Style({
    // stuff from the feature properties
  });
}

Not all of the features contain their own styling information. In this case, i'd like to fall back to the default style.

function style(feature: ol.Feature, resolution: number): ol.style.Style {
  if (!hasOwnStyle(feature)) {
    // defaultStyle is private :(
    return ol.style.Style.defaultStyle();
  }
  return ol.style.Style({
    // stuff from the feature properties
  });
}

Is there a way to access the default style?

Graupel answered 21/11, 2017 at 18:30 Comment(3)
Did you try return feature.getStyle();?????? It should be assigned if not provided.Hecate
@Hecate true, good idea!Graupel
feature.getStyle() is often null, so it is better to use createDefaultStyles(feature, resolution). See my answer below.Erinnerinna
S
4

A style function which returns the default style is assigned to newly created vector layers. You can get the style array by running the function

var defaultStyles = new ol.layer.Vector().getStyleFunction()();

The editing style is a function which requires a feature with geometry

var defaultEditingStyleFunction = new ol.interaction.Select().getOverlay().getStyleFunction();
Saadi answered 12/4, 2019 at 21:10 Comment(0)
B
3

You can set the default style back

import style from 'ol/style';

var fill = new ol.style.Fill({
   color: 'rgba(255,255,255,0.4)'
 });
 var stroke = new ol.style.Stroke({
   color: '#3399CC',
   width: 1.25
 });
 var styles = [
   new ol.style.Style({
    image: new ol.style.Circle({
       fill: fill,
       stroke: stroke,
       radius: 5
     }),
     fill: fill,
     stroke: stroke
   })
 ];

As showed in the documentation.

Bareback answered 13/6, 2018 at 15:22 Comment(0)
E
0
import { FeatureLike } from 'ol/Feature/'
import Style from 'ol/style/Style'
import { createDefaultStyle } from 'ol/style/Style'

function getStyles(feature: FeatureLike, resolution: number): Style[] {
  // return default styles (array)
  return createDefaultStyle(feature, resolution)
}

// or

function getStyle(feature: FeatureLike, resolution: number): Style {
  // return default style
  return createDefaultStyle(feature, resolution)[0]
}
Erinnerinna answered 25/10, 2022 at 16:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.