Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support custom colors #200

Merged
merged 1 commit into from
Apr 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Changed

- Allow custom stroke colors in `addLayer` method. #201

## [v2.2.2] - 2023-09-02

### Fixed
Expand Down
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,21 @@ const colors = {
};
```

Custom colors can be used by providing a `color` option with the desired color value. A color string parser is included
to handle hex, rgb and other formats.
See [color-parse](https://github.com/colorjs/color-parse/tree/master#parsed-strings) for information about supported formats.

```js
// Add a GeoJSON layer with a custom color inside a layer group called "Assets"
const opts = {
title: 'Animals',
url: '/farm/assets/geojson/animal/full',
color: '#FF0000',
group: 'Assets',
};
const layer = myMap.addLayer('geojson', opts);
```

For more complex styles, the `styleFunction` option allows styles to be
defined based on a `feature` and `resolution`
([StyleFunction docs.](https://openlayers.org/en/latest/apidoc/module-ol_style_Style.html#~StyleFunction))
Expand Down
12 changes: 10 additions & 2 deletions src/styles/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,17 @@ const colors = {

// Returns an OpenLayers Style for a given color.
const colorStyles = (color) => {
const rgba = colors[color] ? colors[color] : colors.yellow;
let strokeColor;
if (!color) {
strokeColor = colors.yellow;
} else if (colors[color]) {
strokeColor = colors[color];
} else {
strokeColor = color;
}

const stroke = new Stroke({
color: rgba,
color: strokeColor,
width: 2,
});
const fill = new Fill({
Expand Down
Loading