HTML to APK Builder

ANDROIDAPI REFERENCE

AndroidAPI: GPS location, address lookup and motion sensors

Reference for getLocation, startLocationUpdates, getAddress and startSensor (accelerometer, gyroscope, light, proximity, step counter) with permissions and errors.

Updated:

All methods on this page are Pro. Without Pro, the app sends a general proRequired event; location methods also send their normal result with error: "pro_required".

Method Event Permission
getLocation locationResult location
startLocationUpdates, stopLocationUpdates locationUpdate location
getAddress addressResult none
startSensor, stopSensor, stopAllSensors sensorData, sensorError none (step counter: ACTIVITY_RECOGNITION)

Location permission first

Declare ACCESS_FINE_LOCATION (precise) and/or ACCESS_COARSE_LOCATION (approximate) in Advanced Build → Permissions. The location methods do not show the permission dialog themselves: if neither permission is granted, they return permission_denied immediately. Request it first:

const LOCATION = ['android.permission.ACCESS_FINE_LOCATION', 'android.permission.ACCESS_COARSE_LOCATION'];

function withLocation(start) {
  if (LOCATION.some(p => AndroidAPI.hasPermission(p))) return start();
  window.addEventListener('permissionsResult', function once(e) {
    if (e.detail.callbackId !== 'loc-perm') return;
    window.removeEventListener('permissionsResult', once);
    if (Object.values(e.detail.results).some(Boolean)) start();
    else showMessage('Location permission is needed for this feature.');
  });
  AndroidAPI.requestPermissions(JSON.stringify(LOCATION), 'loc-perm');
}

The user may grant only approximate location. Your app should still work with lower accuracy.

getLocation

AndroidAPI.getLocation(callbackId)

Gets the current position once. If the device has a recent cached position, it can arrive immediately with fromLastKnown: true. Otherwise the app waits for a fresh fix for about 15 seconds.

Result event: locationResult {callbackId, success, latitude, longitude, accuracy, provider, time, fromLastKnown, error}. accuracy is in metres; time is a Unix timestamp in milliseconds.

Errors: pro_required, permission_denied, permission_revoked, provider_disabled (location turned off in system settings), timeout, superseded (a newer getLocation call replaced this one).

window.addEventListener('locationResult', e => {
  const r = e.detail;
  if (r.callbackId !== 'where-am-i') return;
  if (!r.success) {
    const text = { provider_disabled: 'Turn on location in Android settings.',
                   timeout: 'No GPS signal yet. Try again outdoors.' }[r.error] || r.error;
    return showMessage(text);
  }
  showMessage(`${r.latitude.toFixed(5)}, ${r.longitude.toFixed(5)} (±${Math.round(r.accuracy)} m)`);
});
withLocation(() => AndroidAPI.getLocation('where-am-i'));

startLocationUpdates and stopLocationUpdates

AndroidAPI.startLocationUpdates(callbackId)
AndroidAPI.stopLocationUpdates()

Sends a locationUpdate event each time the position changes. Use it for tracking a walk or a delivery route. The first event can carry only status (for example started:gps) and no coordinates; check latitude before using the position.

Event: locationUpdate {callbackId, success, latitude, longitude, accuracy, provider, time, status, error}. Errors: pro_required, permission_denied, permission_revoked, provider_disabled.

Updates stop while your app is in the background. Always call stopLocationUpdates() when tracking ends to save battery.

const path = [];
window.addEventListener('locationUpdate', e => {
  const r = e.detail;
  if (!r.success) return showMessage(r.error);
  if (typeof r.latitude !== 'number') return; // status-only event
  path.push([r.latitude, r.longitude]);
  drawPath(path);
});
startButton.onclick = () => withLocation(() => AndroidAPI.startLocationUpdates('walk'));
stopButton.onclick = () => AndroidAPI.stopLocationUpdates();

getAddress

AndroidAPI.getAddress(latitude, longitude, callbackId)

Converts coordinates to a readable address with the device’s geocoder (reverse geocoding). It needs no permission of its own, but the system geocoder usually needs an internet connection and some devices do not have one.

Result event: addressResult {callbackId, success, latitude, longitude, address, countryCode, error}. Errors: pro_required, geocoder_unavailable, no_result.

window.addEventListener('addressResult', e => {
  const r = e.detail;
  addressField.value = r.success ? r.address : '';
});
AndroidAPI.getAddress(41.0082, 28.9784, 'addr-1');

startSensor

AndroidAPI.startSensor(sensorType, callbackId)

Starts reading a hardware sensor. sensorType is one of:

Name values
accelerometer [x, y, z] acceleration in m/s², gravity included
gyroscope [x, y, z] rotation speed in rad/s
magnetometer [x, y, z] magnetic field in µT
orientation rotation vector (not ready-made compass degrees)
light [lux]
proximity [cm]; many phones only report near/far
stepCounter [steps] since the last device restart

Events: sensorData {callbackId, sensor, values, timestamp, accuracy} many times per second, or sensorError {callbackId, sensor, error} when the type is unknown, the device has no such sensor, or the step-counter permission is missing. timestamp is in nanoseconds since boot, not a date.

Starting the same sensor again replaces the previous listener. Sensors pause while the app is in the background.

// Shake detection
let last = 0;
window.addEventListener('sensorData', e => {
  if (e.detail.sensor !== 'accelerometer') return;
  const [x, y, z] = e.detail.values;
  const force = Math.sqrt(x * x + y * y + z * z);
  if (force > 25 && Date.now() - last > 1000) { last = Date.now(); onShake(); }
});
window.addEventListener('sensorError', e => showMessage(e.detail.sensor + ': ' + e.detail.error));
AndroidAPI.startSensor('accelerometer', 'shake');

Step counter: declare and request android.permission.ACTIVITY_RECOGNITION first. The value counts all steps since the phone restarted, so save the first value as a baseline and show the difference.

let baseline = null;
window.addEventListener('sensorData', e => {
  if (e.detail.sensor !== 'stepCounter') return;
  const total = e.detail.values[0];
  if (baseline === null || total < baseline) baseline = total; // first reading or device restart
  stepsLabel.textContent = total - baseline;
});
AndroidAPI.startSensor('stepCounter', 'steps');

stopSensor and stopAllSensors

AndroidAPI.stopSensor(sensorType)
AndroidAPI.stopAllSensors()

Stop one sensor or all of them. Sensors use battery, so stop them when the screen that needs them closes.

window.addEventListener('pagehide', () => AndroidAPI.stopAllSensors());

Web geolocation

Standard navigator.geolocation.getCurrentPosition() and watchPosition() also work when location permissions are declared; the app asks for permission when the page requests it. They do not require Pro. Use AndroidAPI when you need the explicit error codes, cached-fix information or address lookup.