Chapter 7 of 12 ~13 min read

Geolocation & Device Info

Side-by-side Cordova vs Capacitor — practical migration with working code.


Geolocation

Cordova
// cordova-plugin-geolocation (uses W3C API)
navigator.geolocation.getCurrentPosition(
  function(position) {
    console.log('Lat:', position.coords.latitude);
    console.log('Lon:', position.coords.longitude);
  },
  function(error) {
    console.error('Error:', error.message);
  },
  { enableHighAccuracy: true, timeout: 5000 }
);

// Watch position:
const watchId = navigator.geolocation.watchPosition(
  onSuccess, onError, options
);
Capacitor
import { Geolocation } from '@capacitor/geolocation';

// Get current position
async function getLocation() {
  const coords = await Geolocation.getCurrentPosition({
    enableHighAccuracy: true,
    timeout: 5000,
  });
  console.log('Lat:', coords.coords.latitude);
  console.log('Lon:', coords.coords.longitude);
}

// Watch position
const watchId = await Geolocation.watchPosition(
  { enableHighAccuracy: true },
  (position, err) => {
    if (err) { console.error(err); return; }
    console.log('Updated:', position?.coords.latitude);
  }
);

// Clear watch
await Geolocation.clearWatch({ id: watchId });

Device Information

Cordova Device
// cordova-plugin-device (global 'device' object)
document.addEventListener('deviceready', () => {
  console.log(device.platform);   // "Android"
  console.log(device.version);    // "14"
  console.log(device.model);      // "Pixel 8"
  console.log(device.uuid);       // unique ID
  console.log(device.manufacturer); // "Google"
});
Capacitor Device
import { Device } from '@capacitor/device';

async function getDeviceInfo() {
  const info = await Device.getInfo();
  console.log(info.platform);    // "android"
  console.log(info.osVersion);   // "14"
  console.log(info.model);       // "Pixel 8"
  console.log(info.manufacturer); // "Google"

  // Battery info (separate call):
  const battery = await Device.getBatteryInfo();
  console.log(battery.batteryLevel);  // 0.85
  console.log(battery.isCharging);    // false

  // Unique ID:
  const id = await Device.getId();
  console.log(id.identifier);
}

Permissions Model

Capacitor — check & request permissions
import { Geolocation } from '@capacitor/geolocation';

async function checkAndRequestPermission() {
  // Check current status
  const status = await Geolocation.checkPermissions();
  
  if (status.location === 'denied') {
    // Show explanation UI first, then:
    const req = await Geolocation.requestPermissions();
    if (req.location !== 'granted') {
      // Handle denied — guide user to settings
      return;
    }
  }
  // Now safe to get location
  const pos = await Geolocation.getCurrentPosition();
}