Class Geolocation

java.lang.Object
com.vaadin.flow.component.geolocation.Geolocation
All Implemented Interfaces:
Serializable

public class Geolocation extends Object implements Serializable
Facade for the browser's Geolocation API. Obtain via UI.getGeolocation().

Every entry point on this class is asynchronous: calling it enqueues a request to the browser and returns immediately. The browser answers later (after the user responds to a permission prompt, after the operating system reports a position, or after a timeout), and Flow invokes the callback or updates the signal on the UI thread.

Two usage modes:

Availability check:
  • availabilitySignal() — reactive signal of whether the feature is usable and what permission state the origin has. Subscribe with Signal.effect(owner, ...) to react to changes, or call availabilitySignal().peek() for a snapshot.

Permission prompts. The first time the application asks for a location, the browser shows its own permission dialog. The dialog is controlled by the browser, not by Flow — Flow cannot style it, suppress it, or detect when it is shown. If the user denies the prompt the callback receives a GeolocationError whose errorCode is GeolocationErrorCode.PERMISSION_DENIED.

One-shot example:

 Button locate = new Button("Use my location");
 locate.addClickListener(
         e -> UI.getCurrent().getGeolocation().get(outcome -> {
             switch (outcome) {
             case GeolocationPosition pos -> showNearest(
                     pos.coords().latitude(), pos.coords().longitude());
             case GeolocationError err -> showManualEntry();
             }
         }));
 

Tracking example:

 GeolocationTracker tracker = UI.getCurrent().getGeolocation().track(this);
 Signal.effect(this, () -> {
     switch (tracker.valueSignal().get()) {
     case GeolocationPending p -> {
         // waiting for first reading
     }
     case GeolocationPosition pos ->
         map.setCenter(new Coordinate(pos.coords().longitude(),
                 pos.coords().latitude()));
     case GeolocationError err -> showError(err.message());
     }
 });
 
See Also:
  • Constructor Details

    • Geolocation

      public Geolocation(UI ui)
      Creates a new Geolocation facade bound to the given UI.

      Framework-only. Application code obtains the instance via UI.getGeolocation() and should not instantiate this class directly — attempting to create a second instance for a UI that already has one throws.

      The underlying GeolocationClient is resolved through Lookup: if a GeolocationClientFactory is registered, its GeolocationClientFactory.create(UI) produces the client. Otherwise the built-in browser-backed client is used.

      Parameters:
      ui - the UI this facade belongs to
      Throws:
      IllegalStateException - if the UI already has a Geolocation facade
  • Method Details

    • get

      public void get(SerializableConsumer<GeolocationOutcome> callback)
      Requests the user's current position once. The callback receives a GeolocationOutcome — either a GeolocationPosition or a GeolocationError. Use switch pattern matching on the outcome; no dead "pending" arm is needed because one-shot requests never produce that value.

      The call returns immediately. The browser may show a permission dialog on the first call; after the user responds, the callback is invoked on the UI thread.

      Parameters:
      callback - invoked with the outcome once the browser reports it
    • get

      public void get(@Nullable GeolocationOptions options, SerializableConsumer<GeolocationOutcome> callback)
      Requests the user's current position once with tuning options. Use this to trade accuracy for battery/speed or to accept a recent cached reading. See GeolocationOptions for the available settings.

      The call returns immediately. The browser may show a permission dialog on the first call; after the user responds, the callback is invoked on the UI thread.

      Parameters:
      options - accuracy / timeout / cache-age tuning, or null to use the browser defaults
      callback - invoked with the outcome once the browser reports it
    • track

      public GeolocationTracker track(Component owner)
      Starts continuously watching the user's position, tied to the owner component's lifecycle.

      The browser reports new positions whenever it detects movement. Each report is delivered to the returned tracker's valueSignal() signal on the UI thread. The initial value is GeolocationPending until the first reading arrives, then transitions to GeolocationPosition (updated on every subsequent reading) or GeolocationError.

      The underlying browser watch is automatically cancelled when owner detaches, so the application does not need to write cleanup code for navigation. For cancelling while the view is still attached (e.g. a "Stop tracking" button), call GeolocationTracker.stop() on the returned tracker.

      Permission-revoke caveat. If the user revokes geolocation permission while a watch is active and then grants it again, the browser silently stops delivering position updates to the existing watch — this is the W3C Geolocation API's documented behavior across browsers, not a Flow-specific limitation. To recover after a revoke/regrant cycle, call GeolocationTracker.stop() followed by GeolocationTracker.resume(), which installs a fresh browser watch. Applications that want this to happen automatically can subscribe to availabilitySignal() with Signal.effect(owner, ...) and trigger the stop/resume when the availability transitions back to GRANTED.

      Parameters:
      owner - the component that owns this tracking session; detaching the component automatically stops the watch
      Returns:
      a tracker whose GeolocationTracker.valueSignal() reports progress and whose GeolocationTracker.stop() cancels the watch
    • track

      public GeolocationTracker track(Component owner, @Nullable GeolocationOptions options)
      Starts continuously watching the user's position with tuning options, tied to the owner component's lifecycle. Behaves like track(Component) but lets the caller request high accuracy, set a failure timeout, or accept cached readings. See GeolocationOptions for the available settings.
      Parameters:
      owner - the component that owns this tracking session; detaching the component automatically stops the watch
      options - accuracy / timeout / cache-age tuning, or null to use the browser defaults
      Returns:
      a tracker whose GeolocationTracker.valueSignal() reports progress and whose GeolocationTracker.stop() cancels the watch
    • availabilitySignal

      public Signal<GeolocationAvailability> availabilitySignal()
      Returns a read-only signal holding the current geolocation availability — whether the Geolocation API is usable in this context and, if so, what permission state the origin has.

      Subscribe with Signal.effect(owner, ...) to react to availability changes (e.g. disabling a location button when the user revokes permission). For a snapshot read, call availabilitySignal().peek(); in an effect or reactive context, call availabilitySignal().get().

      The signal starts as UNKNOWN, transitions to the value reported during the initial client bootstrap, and updates on every get(com.vaadin.flow.function.SerializableConsumer<com.vaadin.flow.component.geolocation.GeolocationOutcome>) / track(com.vaadin.flow.component.Component) outcome and on browser permission-change events where supported.

      Reliability caveats. The value is best-effort, not authoritative — it reflects what the browser last reported, and can be briefly stale in these cases:

      Treat the value as a hint for pre-rendering decisions (e.g. auto-fetching on return visits, hiding controls in unsupported contexts). For critical paths, call get(com.vaadin.flow.function.SerializableConsumer<com.vaadin.flow.component.geolocation.GeolocationOutcome>) and handle the authoritative result in the callback.
      Returns:
      the availability signal