Vector Tile select
by Vladimir Vershinin
HTML
<script src="https://unpkg.com/vue@latest/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io/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">
<div id="app">
<select v-model="vtSelectMode">
<option value="single">Single select</option>
<option value="multi">Multi select</option>
</select>
<vl-map ref="map" @click="onMapClick">
<vl-view :zoom.sync="zoom" :center.sync="center"></vl-view>
<vl-layer-tile>
<vl-source-osm></vl-source-osm>
</vl-layer-tile>
<vl-layer-vector-tile ref="vtLayer" :declutter="true">
<vl-source-vector-tile :format-factory="vtFormatFactory" :url="vtUrl"></vl-source-vector-tile>
<vl-style-func :factory="vtStyleFuncFactory"></vl-style-func>
</vl-layer-vector-tile>
</vl-map>
</div>
CSS
html, body, #app {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
JavaScript
new Vue({
el: '#app',
data () {
return {
zoom: 3,
center: [0, 0],
vtUrl: 'https://ahocevar.com/geoserver/gwc/service/tms/1.0.0/' +
'ne:ne_10m_admin_0_countries@EPSG%3A900913@pbf/{z}/{x}/{-y}.pbf',
vtIdProp: 'iso_a3',
vtSelection: {},
vtSelectMode: 'single',
}
},
methods: {
vtFormatFactory () {
return new ol.format.MVT()
},
vtStyleFuncFactory () {
return feature => {
let selected = !!this.vtSelection[feature.get(this.vtIdProp)]
return [
new ol.style.Style({
stroke: new ol.style.Stroke({
color: selected ? 'rgba(200,20,20,0.8)' : 'gray',
width: selected ? 2 : 1,
}),
fill: new ol.style.Fill({
color: selected ? 'rgba(200,20,20,0.2)' : 'rgba(20,20,20,0.9)',
})
})
]
}
},
onMapClick (evt) {
let features = this.$refs.map.$map.getFeaturesAtPixel(evt.pixel)
if (!features) {
this.vtSelection = {}
// force redraw of layer style
this.$refs.vtLayer.refresh()
return
}
let feature = features[0]
let fid = feature.get(this.vtIdProp)
if (this.vtSelectMode === 'single') {
this.vtSelection = {}
}
// add selected feature to lookup
this.vtSelection[fid] = feature
// force redraw of layer style
this.$refs.vtLayer.refresh()
},
},
})