Drag and drop features

by Vladimir Vershinin

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.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://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.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">
  <div>Pointer coordinate: {{ pointerCoord }}</div>
  <div>Features: {{ features }}</div>
  <vl-map ref="map" data-projection="EPSG:4326" @created="onMapCreated" @pointermove="onPointerMove">
    <vl-view ref="mapView" :zoom.sync="zoom" :center.sync="center"></vl-view>

    <vl-layer-tile>
      <vl-source-osm :crossOrigin="null" />
    </vl-layer-tile>
  
    <vl-layer-vector id="features">
      <vl-source-vector ref="featuresSource" :features.sync="features"></vl-source-vector>
    </vl-layer-vector>
  </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],
      features: [],
      pointerCoord: [],
      pointerDragCoord: [],
    }
  },
  methods: {
  	onMapCreated (mapVm) {
    	const dd = new ol.interaction.DragAndDrop({
      	formatConstructors: [
        	ol.format.GeoJSON,
        ],
      })
    	mapVm.addInteraction(dd)
      
      dd.on('addfeatures', evt => {
	      this.pointerDragCoord = this.pointerCoord.slice()
      	this.$refs.featuresSource.addFeatures(evt.features)
      })
    },
    onPointerMove (evt) {
    	this.pointerCoord = evt.coordinate
    },
  },
})