The geolocation feature in TouchKit allows receiving the geographical location from the mobile device. The browser will ask the user to confirm that the web site is allowed to get the location information. Tapping Share Location gives the permission. The browser will give the position acquired by GPS, cellular positioning, or Wi-Fi positioning, as enabled in the device.

Geolocation is requested by calling the static Geolocator.detect() method. You need to provide a PositionCallback handler that is called when the device has an answer for your request. If the geolocation request succeeded, onSuccess() is called. Otherwise, e.g . if the user didn't allow sharing of his location, onFailure is called. The geolocation data is provided in a Position object.

Geolocator.detect(new PositionCallback() {
    public void onSuccess(Position position) {
        double latitude  = position.getLatitude();
        double longitude = position.getLongitude();
        double accuracy  = position.getAccuracy();

        ...
    }

    public void onFailure(int errorCode) {
        ...
    }
});

The position is given as degrees with fractions. The longitude is positive to East and negative to West of the Prime Meridian passing through Greenwich, following the convention for coordinate systems. The accuracy is given in meters. In addition to the above data, the following are also provided:

  1. Altitude
  2. Altitude accuracy
  3. Heading
  4. Speed

If any of the position data is unavailable, its value will be zero.

The onFailure() is called if the positioning fails for some reason. The errorCode explains the reason. Error 1 is returned if the permission was denied, 2 if the position is unavailable, 3 on positioning timeout, and 0 on an unknown error.

Notice that geolocation can take significant time, depending on the location method used by the device. With Wi-Fi and cellular positioning, the time is usually less than 30 seconds. With GPS, it can reach minutes or longer, especially if the reception is bad. However, once a location fix has been made, updates to the location will be faster. If you are making navigation software, you need to update the position data fairly frequently by calling Geolocator.detect() multiple times.