Ilia Choly
Ilia Choly

Reputation: 18557

Access default OpenLayers style

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?

Upvotes: 6

Views: 3878

Answers (3)

Andrey
Andrey

Reputation: 1623

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]
}

Upvotes: 0

Doctor
Doctor

Reputation: 7996

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.

Upvotes: 3

Mike
Mike

Reputation: 17982

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();

Upvotes: 4

Related Questions