Select vector tile feature

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">
  <vl-map ref="map" data-projection="EPSG:4326" @singleclick="onMapClick">
    <vl-view ref="mapView" :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="vectorTileLayer">
      <vl-source-vector-tile :url="url"></vl-source-vector-tile>
      <vl-style-func :factory="createVectorTileStyleFunc"></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: 2,
      center: [0, 0],
      url: 'https://ahocevar.com/geoserver/gwc/service/tms/1.0.0/ne:ne_10m_admin_0_countries@EPSG%3A900913@pbf/{z}/{x}/{-y}.pbf',
      selection: {},
    }
  },
  methods: {
  	onMapClick (evt) {
    	this.selection = {}
    
    	let features = this.$refs.map.getFeaturesAtPixel(evt.pixel)
      console.log(features)
      if (features && features.length > 0 ) {
      	let feature = features[0]
        if (feature) {
        	// this.selection[feature.getId()] = true
          this.selection[feature.get('iso_a3')] = true
				}
      }
      
      this.$refs.vectorTileLayer.refresh()
    },
    createVectorTileStyleFunc () {
    	return feature => {
      	// let selected = this.selection[feature.getId()]
        let selected = this.selection[feature.get('iso_a3')]
        
        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)',
            }),
          }),
        ]
      }
    },
  },
})