TransWikia.com

How to check for OL events in Vue?

Geographic Information Systems Asked on June 6, 2021

I would like to observe things like maps.on('moveend') to update zoom level or center values. Currently I have a "construct" made up of computed params and watcher functions like this:

export default {
  [...],
  // Computed values are saved / read from vuex store
  computed: {
    currentLatLon: {
      get () {
        const obj = {
          lat: this.$store.getters.getCurrentLat,
          lon: this.$store.getters.getCurrentLon
        }
        return obj
      }
    },
    moveEnd: {
      get () {
        const val = this.olMap !== null
          ? this.olMap.on('moveend', () => {
              console.log('moveEnd; do something... getCenter()...'))
            }
          : false
        return val
      }
    }
  },
  watch: {
    currentLatLon (value) {
      console.log('watcher currentLatLon invoked: value =', value)
      // this.zoomToCurrentLocation()
    },
    moveEnd (value) {
      console.log('moveEnd: value =', value)
    }
  }
}

codesandbox with minimal code:
https://codesandbox.io/s/openlayers-getzoom-74gnw?file=/src/components/MapContainer.vue

It works so far. But I am unsure, because it seems to be "double the trouble".

Is there a better way to observe Openlayers events in Vue?

One Answer

I answer this myself, maybe one day it helps somebody else:

OpenLayers event listeners are setup in Vue's "mounted" lifecycle hook. The function such an event listener calls is then defined regularly in "methods".

Example (Vue 2):

export default {
  data(() => {
    olMap: null,
    geolocation: null,
    [....]
  },
  mounted() {
    this.olMap = new Map({ ... })
    this.olMap.on('moveend', this.onMoveEnd)

    this.geolocation = new Geolocation({ ... })
    this.geolocation.on('change', this.onChange)
    this.geolocation.on('change:accuracyGeometry', this.onChangeAccuracyGeometry)
    [...]
    this.geolocation.on('error', this.onError)
  },
  methods: {
    onMoveEnd () { ... }
    onMoveChange () { ... }
    onChangeAccuracyGeometry () { ... }
    onError () { ... }
  }
}

Correct answer by Robert Wildling on June 6, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP