Harrison Cramer
Harrison Cramer

Reputation: 4506

MapboxGl Distinguishing Between "Move" and "Fly" Event

In MapboxGL JS, is it possible to watch a "flyTo" event triggered by the geolocate API, and not the user moving around the screen manually by dragging the map?

I'm trying to trigger an action in my application only when the user successfully enters a search into the Geolocation controller. The map has a movestart event that works for this, but it also captures the user's movement of the screen via the cursor or their finger.

import Geocoder from "@mapbox/mapbox-gl-geocoder";
const geocoder = new Geocoder({
  countries: "us",
  accessToken: mapboxGl.accessToken,
  mapboxgl: mapboxGl,
  marker: false,
  render: function (item) {
    return `<span class='geocoder-dropdown-text'>${item.text}</span>`;
  },
});

map.on("movestart", (e) => {
  // The problem is this event is too broad...
});

Is it possible to only listen for the "flying" event when the Geolocation API fires, or specifically provide a callback to the Geocoder that will fire when the animation begins?

Upvotes: 2

Views: 764

Answers (2)

Fredrik Jungstedt
Fredrik Jungstedt

Reputation: 527

Looking at the emitted event, there's an originalEvent property which is only set when the event source is native, ie TouchStart, MouseWheel etc.

That way one could distinguish between user movement and programmatic movement like so:

map.on('movestart', (e) => {
    const isUserMovement = 'originalEvent' in e;
})

Upvotes: 1

0x4e
0x4e

Reputation: 106

You can create a variable flying and set it to true when the fly starts. Then you can listen for events movestart or moveenv and check if it is dragged by a user or triggered fly event.

let flying = false;

map.on("flystart", function () 
  flying = true;
});

map.on("flyend", function () {
  flying = false;
});

map.on("moveend", function () {
  if (flying) {
    map.fire("flyend");
  }
});

function fly() {
  map.flyTo({
    center: [....],
  });
  map.fire("flystart");
}

Fiddle: https://jsfiddle.net/wdtc91qo/

Upvotes: 3

Related Questions