Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 37 ยท Capacitor and Native APIs

Geolocation, Device Info and Network Status

Read the user's position with the Capacitor Geolocation plugin, watch it over time, detect online and offline state, inspect the device and handle app lifecycle events.

Many apps need to know where they are, what they run on and whether they are online. Capacitor answers these with four small plugins: Geolocation, Device, Network and App. Each one is a handful of calls, but the details (accuracy, battery, permission wording, listeners that must be removed) decide whether the feature feels professional.

You will learn the real API, then practice the logic with stand-ins you can run: a distance calculation, a position watcher and a connectivity listener.

Geolocation

Terminal
npm install @capacitor/geolocation @capacitor/network @capacitor/device @capacitor/app
npx cap sync

One position, read-only real code:

TypeScript
import { Geolocation } from '@capacitor/geolocation';

export async function whereAmI() {
  const permission = await Geolocation.requestPermissions();
  if (permission.location === 'denied') {
    throw new Error('Location permission denied');
  }
  const position = await Geolocation.getCurrentPosition({
    enableHighAccuracy: false,   // coarse is faster and uses less battery
    timeout: 10_000,
  });
  const { latitude, longitude, accuracy } = position.coords;
  return { latitude, longitude, accuracy };
}

enableHighAccuracy: true turns on GPS. It takes longer and drains the battery, so use it only when you really need meters, for example while navigating. Android 12 and later let users give only approximate location; the plugin reports this as coarseLocation. iOS needs NSLocationWhenInUseUsageDescription in Info.plist, and Android needs the location permissions in the manifest.

Watching the position

TypeScript
const id = await Geolocation.watchPosition({ enableHighAccuracy: true }, (position, err) => {
  if (err) { console.error(err); return; }
  updateMap(position!.coords.latitude, position!.coords.longitude);
});

// when the screen is left
await Geolocation.clearWatch({ id });

Every watch must be cleared. In an Ionic page that means using ionViewWillLeave or the framework's destroy hook. A forgotten watch keeps the GPS on in the background and shows up in battery reports.

Working with coordinates

The device gives latitude and longitude. Common tasks are "how far is this place?" and "which saved place is nearest?". The haversine formula gives the distance over the Earth's surface.

JS Distance and nearest place

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Network

The Network plugin reports the connection type and fires an event when it changes. Real code:

TypeScript
import { Network } from '@capacitor/network';

const status = await Network.getStatus();   // { connected: true, connectionType: 'wifi' }

const handle = await Network.addListener('networkStatusChange', (s) => {
  console.log('Online?', s.connected, s.connectionType);
});
// later: await handle.remove();

connected says a network interface is up, not that your server is reachable. A cafรฉ Wi-Fi with a login page reports connected: true. Treat the flag as a hint, and always handle failed requests. The offline chapter lesson, Offline First and Sync, builds on this.

JS A connectivity listener with cleanup

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Device and App

TypeScript
import { Device } from '@capacitor/device';
import { App } from '@capacitor/app';

const info = await Device.getInfo();    // model, platform, osVersion, manufacturer, isVirtual
const battery = await Device.getBatteryInfo(); // { batteryLevel: 0.82, isCharging: false }
const lang = await Device.getLanguageCode();   // { value: 'en' }
const { identifier } = await Device.getId();   // stable per app install

App.addListener('appStateChange', ({ isActive }) => {
  if (!isActive) saveDraft(); else refreshData();
});
App.addListener('backButton', ({ canGoBack }) => {
  if (!canGoBack) App.exitApp();        // Android hardware back
});

appStateChange is where you pause timers and flush unsaved work: mobile systems can end a background app without warning. The Android back button needs handling in apps with custom navigation; the navigation chapter explains how Ionic's router uses it.

Device.getId() is not an advertising id and cannot track a person across apps. Treat it as a technical install identifier and mention any data you collect in your privacy policy.

Choosing the right accuracy

flowchart TD
  A["Need location?"] --> B{"Meters matter?"}
  B -->|"No: city, weather"| C["getCurrentPosition, low accuracy"]
  B -->|"Yes: tracking, navigation"| D["watchPosition, high accuracy"]
  D --> E["Clear the watch on leave"]
  C --> F["Cache result, ask rarely"]

Coarse location answers most questions and is kinder to the battery.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does enableHighAccuracy: true do?

    High accuracy uses GPS, which is slower and uses more power.
  2. 2. What must you do with the id returned by watchPosition?

    An uncleared watch keeps location services running.
  3. 3. Network status says connected: true. What is guaranteed?

    A captive portal or a down server still shows as connected, so requests must handle failure.
  4. 4. Which event lets you save work when the app goes to the background?

    appStateChange reports isActive false when the app leaves the foreground.

Summary

  • Geolocation offers one-shot and watched positions; keep accuracy as low as the feature allows and always clear watches.
  • Use the haversine formula for distances between coordinates.
  • Network tells you about the interface, not about your server; listen with networkStatusChange.
  • Device and App give model, battery, language, state and back-button events.
  • Remove listeners you add.

Next: Push Notifications and Haptics