1

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(...)").

1

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);
});
1
  • Thank you, especially for the unByKey tip! Mar 20 at 13:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.