Feature style
by Vladimir Vershinin
HTML
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v5.3.0/build/ol.js"></script>
<script src="https://unpkg.com/[email protected]/lib/index.umd.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/lib/style.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
<div id="app">
<div>
<span v-if="message">
{{ message }}
</span>
<div v-if="features.length > 0">
<label v-for="feature in features" :key="feature.id">
<input type="checkbox" v-model="feature.properties.active">
Feature {{ feature.id }}
</label>
</div>
</div>
<vl-map ref="map" data-projection="EPSG:4326">
<vl-view ref="mapView" :zoom.sync="zoom" :center.sync="center"></vl-view>
<vl-layer-tile id="osm">
<vl-source-osm></vl-source-osm>
</vl-layer-tile>
<vl-layer-vector>
<vl-source-vector ref="geojsonSource" url="https://gist.githubusercontent.com/ghettovoice/37ef37dd571ed39b0985c16560b157d3/raw/3499326b779d6c2c2e28ec49c9e492be3bbf8f0f/map.geojson" :features.sync="features"></vl-source-vector>
<vl-style-func :factory="styleFuncFactory"></vl-style-func>
</vl-layer-vector>
</vl-map>
</div>
CSS
html, body, #app {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.layers {
position: absolute;
top: 10px;
left: 50px;
z-index: 1;
}
JavaScript
new Vue({
el: '#app',
data() {
return {
zoom: 2,
center: [0, 0],
sourceFeatures: [],
message: 'Loading...',
}
},
computed: {
features: {
get () {
return this.sourceFeatures
},
set (features) {
this.sourceFeatures = features.map(f => JSON.parse(JSON.stringify(f)))
},
},
},
watch: {
features: _.debounce(function() {
this.message = `Loaded ${this.features.length}`
this.$refs.mapView.$view.fit(
this.$refs.geojsonSource.$source.getExtent(), {
duration: 1000,
},
)
}, 100),
},
methods: {
styleFuncFactory() {
const defaultFill = new ol.style.Fill({
color: [255, 255, 255, 0.5]
})
const defaultStroke = new ol.style.Stroke({
color: 'blue',
width: 1.25,
})
const defaultStyle = new ol.style.Style({
fill: defaultFill,
stroke: defaultStroke,
image: new ol.style.Circle({
radius: 5,
fill: defaultFill,
stroke: defaultStroke,
}),
})
const activeStroke = new ol.style.Stroke({
color: 'green',
width: 2
})
const activestyle = new ol.style.Style({
fill: defaultFill,
stroke: activeStroke,
image: new ol.style.Circle({
radius: 10,
fill: defaultFill,
stroke: activeStroke,
}),
})
return feature => {
if (feature.get('active')) {
return activestyle
}
return defaultStyle
}
}
},
})