Demonstrates rule based styling.
To style all features in a layer in the same way, you can use a symbolizer object with literal values as shown below for the land layer. In this case, all features have the same fill color.
To style features in a layer based on a feature property, an expression can be provided in a symbolizer instead of literal values. In the first populated places layer below, the circle radius is based on the scalerank
property.
To conditionally apply different symbolizers based on a feature property, a list of rules can be provided. Each rule can have a filter
expression. If this expression evaluates to true, the rule's style
is applied. A rule with else: true
applies if no previous rules have applied. The populated place labels are rendered with a list of rules given to the third layer.
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import Layer from 'ol/layer/Vector.js';
import Source from 'ol/source/Vector.js';
const format = new GeoJSON();
const map = new Map({
layers: [
new Layer({
background: '#1a2b39',
source: new Source({
url: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_110m_land.geojson',
format,
}),
style: {
'fill-color': 'darkgray',
},
}),
new Layer({
source: new Source({
url: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_50m_populated_places_simple.geojson',
format,
}),
style: {
'circle-radius': ['get', 'scalerank'],
'circle-fill-color': 'gray',
'circle-stroke-color': 'white',
'circle-stroke-width': 0.5,
},
}),
new Layer({
source: new Source({
url: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_50m_populated_places_simple.geojson',
format,
}),
declutter: true,
style: [
{
filter: ['>', ['get', 'pop_max'], 10_000_000],
style: {
'text-value': [
'concat',
['get', 'adm1name'],
', ',
['get', 'adm0name'],
],
'text-font': '16px sans-serif',
'text-fill-color': 'white',
'text-stroke-color': 'gray',
'text-stroke-width': 2,
},
},
{
else: true,
filter: ['>', ['get', 'pop_max'], 5_000_000],
style: {
'text-value': ['get', 'nameascii'],
'text-font': '12px sans-serif',
'text-fill-color': 'white',
'text-stroke-color': 'gray',
'text-stroke-width': 2,
},
},
],
}),
],
target: 'map',
view: new View({
center: [0, 0],
zoom: 1,
}),
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Style Expressions</title>
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script type="module" src="main.js"></script>
</body>
</html>
{
"name": "style-expressions",
"dependencies": {
"ol": "10.5.0"
},
"devDependencies": {
"vite": "^3.2.3"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}