Geolocation

The Geolocation class can be used to register events that get the geographical position of the device with a timestamp.

Instruction:

  1. Creating the geolocation object. This must attach to our website in order to listen to events:

    // Wir befinden uns gerade im Konstruktor einer View
    final Geolocation geolocation = new Geolocation(this);
  2. After that we can register our listeners:

    // Gibt die Latitude und Longitude in der Konsole aus
    geolocation.addPositionListener(position -> {
      final Coordinates coordinates = position.getCoords();
      System.out.println(String.format("Coordinates: lat=%f, long=%f", coordinates.getLatitude(), coordinates.getLongitude()));
    });
    
    // Gebe die Fehlermeldung aus, falls etwas nicht funktioniert
    geolocation.addPositionErrorConsumer(error -> {
      System.err.println(error.getMessage());
    });
  3. If the position is to be output only once, getCurrentPosition(PositionOptions) can be called:

    geolocation.getCurrentPosition(PositionOptions.Default());
  4. To start listening to the position, watchPosition(PositionOptions) can be called:

    geolocation.watchPosition(PositionOptions.Default());

Note:

  • Latitude, Longitude and Accuracy are always set.

  • Altitude, Altitude, Accuracy, Heading and Speed do not have to be set by the browser, so these values can also contain zero!