Select features

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">
    <vl-view ref="view" :zoom.sync="zoom" :center.sync="center"></vl-view>

    <vl-layer-tile>
      <vl-source-osm></vl-source-osm>
    </vl-layer-tile>
    
    <vl-layer-vector id="events">
      <vl-source-vector :features.sync="features"></vl-source-vector>
    </vl-layer-vector>
    
    <vl-layer-vector id="event-lines" :visible="eventLines.length > 0">
      <vl-source-vector :features.sync="eventLines"></vl-source-vector>
    </vl-layer-vector>
    
    <vl-interaction-select :features.sync="selectedFeatures"></vl-interaction-select>
    
    <vl-overlay v-for="feature in selectedFeaturesWithData" :key="feature.id" :position="feature.geometry.coordinates">
      <div style="background: #fff">
        Feature ID: {{ feature.id }}
        Name: {{ feature.properties.name }}
      </div>
    </vl-overlay>
  </vl-map>
</div>

CSS

html,
body,
#app {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

#app {
  display: flex;
  flex-direction: column;
}

.vl-map {
  overflow: hidden;
}

JavaScript

new Vue({
  el: '#app',
  data() {
    return {
      zoom: 2,
      center: [0, 0],
      features: [
      	{
        	type: 'Feature',
          geometry: {
          	type: 'Point',
            coordinates: [10, 10]
          },
        },
        {
        	type: 'Feature',
          geometry: {
          	type: 'Point',
            coordinates: [-10, -10]
          },
        },
      ],
      selectedFeatures: [],
      selectedFeaturesWithData: [],
    }
  },
  computed: {
  	eventLines () {
    	return this.selectedFeaturesWithData.reduce((lines, feature) => {
      	return lines.concat(feature.properties.lines.map(line => ({
        	type: 'Feature',
          geometry: {
          	type: 'LineString',
            coordinates: line,
          },
        })))
      }, [])
    },
  },
  watch: {
  	selectedFeatures (features) {
			// load additional data
			console.log(features)
      
			this.selectedFeaturesWithData = features.map(feature => {
      	feature.properties = {
        	name: 'qwerty',
          lines: [
          	[[5, 5], [0, 5]],
            [[15, 15], [20, 20]]
          ]
        }
        return feature
      })
		},
  },
})