Draw events

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>
      <vl-source-vector ident="drawn" :features.sync="features"></vl-source-vector>
      <vl-style-func :factory="createStyleFunc"></vl-style-func>
    </vl-layer-vector>

    <vl-interaction-draw source="drawn" type="Polygon" @drawstart="onDrawStart">
      <vl-style-func :factory="createStyleFunc"></vl-style-func>
    </vl-interaction-draw>
  </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: [],
    }
  },
  methods: {
    createStyleFunc() {
    	const redStyle = VueLayers.olExt.createStyle({
      	fillColor: 'red',
        strokeColor: 'black'
      })
      const greenStyle = VueLayers.olExt.createStyle({
      	fillColor: 'green',
        strokeColor: 'black'
      })
    
      return feature => {
				if (feature.get('active')) {
        	return greenStyle
        }
        return redStyle
      }
    },
    onDrawStart (evt) {
			evt.feature.set('active', !!Math.round(Math.random()))
    }
  },
})