TransWikia.com

Using "once" event in OpenLayers

Geographic Information Systems Asked by Robert Wildling on May 2, 2021

In OpenLayers, the geolocation object has a "once" event:
https://openlayers.org/en/latest/apidoc/module-ol_Geolocation-Geolocation.html#once

How can I use this event?

This throws an error:

// Vue
export default {
 data() {
  return { geolocation: null }
 },
 mounted() {
  this.geolocation = new Geolocation({ ... })
 },
 methods: {
  geolocAtPoint() {
    // Here I would expect geolocation data that is return only once... 
    console.log('this.geolocation.once("change:position") =', 
    this.geolocation.once('change:position'))
  }
}

Eventually, I would like to be able to tab on the map and get the geolocation data of that very point (corresponding to the vanilla "navigator.geolocation.getCurrentPosition(…)").

One Answer

The way to listen to your event once is to use

this.geolocation.once('change', function(evt) {
  console.log(geolocation.getPosition());
});

Often, the time to acquire the position, listening only once is not enough. In this case, it's better to listen to event and remove the event when you are sure you got the "right" info like the position after your device got enough precision

import {unByKey} from 'ol/Observable';

var myeventkey = this.geolocation.on('change', function(evt) {
  console.log(geolocation.getPosition());
  # When happy and you feel you can remove the event,
  # use an if condition wrapping
  # unByKey(myeventkey);
});

Correct answer by ThomasG77 on May 2, 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