@capgo/capacitor-compass

中文文档
8.1.24发布于 2026/10/15MPL-2.0TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 4.6万

Native compass heading plugin for Capacitor

原始使用文档
文档目录26 节
  1. ➡️ Get started for free
  2. Key features
  3. Why Capacitor Compass?
  4. Compatibility
  5. Install
  6. Requirements
  7. iOS
  8. Android
  9. Usage
  10. API
  11. getCurrentHeading()
  12. getPluginVersion()
  13. startListening(...)
  14. stopListening()
  15. addListener('headingChange', ...)
  16. addListener('accuracyChange', ...)
  17. removeAllListeners()
  18. checkPermissions()
  19. requestPermissions()
  20. watchAccuracy()
  21. unwatchAccuracy()
  22. getAccuracy()
  23. Interfaces
  24. Type Aliases
  25. Enums
  26. Credits

@capgo/capacitor-compass

Get the device compass heading in degrees on iOS and Android, as a one-off reading or a live stream. Point users toward a place, rotate a map or build a qibla finder.

Capgo - Build Capacitor apps with AI, ship updates instantly

Capgo: push fixes to your Capacitor users in minutes, build signed iOS and Android apps without a Mac, and roll back in one click.

➡️ Get started for free

14-day unlimited free trial. No credit card required

🤖 Building with an AI coding agent? Install Capgo skills so Claude Code, Codex, Cursor, Copilot, or Gemini CLI know how to install and use @capgo/capacitor-compass in your Capacitor app: npx skills add Cap-go/capgo-skills. Then ask your agent: "Add @capgo/capacitor-compass to my Capacitor app and wire it up." Agent setup guides · Hosted MCP

@capgo/capacitor-compass for Capacitor apps

Key features

  • Current heading: getCurrentHeading() returns the heading in degrees.
  • Live updates: startListening() emits headingChange events, stopListening() stops them.
  • Accuracy: watchAccuracy(), getAccuracy() and the accuracyChange event so you can ask users to calibrate.
  • Permissions: checkPermissions() and requestPermissions().
  • Platforms: iOS and Android. iOS uses Core Location heading, Android uses the device sensors. Not available on web.

Why Capacitor Compass?

The official Capacitor Motion API relies on web APIs for compass/heading data, which provides a suboptimal developer experience:

  • Inconsistent behavior across platforms
  • Additional permissions handling through web APIs
  • Limited accuracy compared to native implementations
  • Poor performance on some devices
  • No accuracy monitoring to ensure reliable compass readings

This plugin provides true native compass functionality using:

  • iOS: CLLocationManager for accurate heading data via CoreLocation
  • Android: Hardware sensors (accelerometer + magnetometer) for precise bearing calculation
  • Accuracy monitoring: Monitor compass accuracy on Android and prompt users to calibrate when needed
  • Event-based API: Modern addListener pattern for real-time heading updates

Essential for navigation apps, augmented reality, location-based games, and any app needing accurate compass heading.

Compatibility

Plugin versionCapacitor compatibilityMaintained
v8.*.*v8.*.*✅
v7.*.*v7.*.*On demand
v6.*.*v6.*.*❌
v5.*.*v5.*.*❌

Note: The major version of this plugin follows the major version of Capacitor. Use the version that matches your Capacitor installation (e.g., plugin v8 for Capacitor 8). Only the latest major version is actively maintained.

Install

You can use our AI-Assisted Setup to install the plugin. Add the Capgo skills to your AI tool using the following command:

npx skills add https://github.com/cap-go/capacitor-skills --skill capacitor-plugins

Then use the following prompt:

Use the `capacitor-plugins` skill from `cap-go/capacitor-skills` to install the `@capgo/capacitor-compass` plugin in my project.

If you prefer Manual Setup, install the plugin by running the following commands and follow the platform-specific instructions below:

npm install @capgo/capacitor-compass
npx cap sync

Requirements

iOS

Add the following to your Info.plist:

<key>NSLocationWhenInUseUsageDescription</key>
<string>We need access to your location to determine compass heading</string>

Android

No additional setup required. The plugin uses the device's accelerometer and magnetometer sensors.

Usage

import { CapgoCompass, CompassAccuracy } from '@capgo/capacitor-compass';

// Get current heading once
const { value } = await CapgoCompass.getCurrentHeading();
console.log('Current heading:', value, 'degrees');

// Listen for continuous heading updates
const handle = await CapgoCompass.addListener('headingChange', (event) => {
  console.log('Heading:', event.value, 'degrees');
});

// Start the compass sensor
await CapgoCompass.startListening();

// Monitor compass accuracy (Android only)
const accuracyHandle = await CapgoCompass.addListener('accuracyChange', (event) => {
  console.log('Compass accuracy:', event.accuracy);
  if (event.accuracy < CompassAccuracy.MEDIUM) {
    console.log('Compass needs calibration');
    // Show your own custom UI to prompt user to calibrate
  }
});

// Start accuracy monitoring
await CapgoCompass.watchAccuracy();

// Get current accuracy
const { accuracy } = await CapgoCompass.getAccuracy();
console.log('Current accuracy:', accuracy);

// Later: stop listening
await CapgoCompass.stopListening();
await CapgoCompass.unwatchAccuracy();
await handle.remove();
await accuracyHandle.remove();

API

Capacitor Compass Plugin interface for reading device compass heading.

getCurrentHeading()

getCurrentHeading() => Promise<CompassHeading>

Get the current compass heading in degrees. On iOS, the heading is updated in the background, and the latest value is returned. On Android, the heading is calculated when the method is called using accelerometer and magnetometer sensors. Not implemented on Web.

Returns: Promise<CompassHeading>

Since: 7.0.0


getPluginVersion()

getPluginVersion() => Promise<{ version: string; }>

Get the native Capacitor plugin version.

Returns: Promise<{ version: string; }>

Since: 7.0.0


startListening(...)

startListening(options?: ListeningOptions | undefined) => Promise<void>

Start listening for compass heading changes via events. This starts the compass sensors and emits 'headingChange' events.

ParamTypeDescription
optionsListeningOptions- Optional configuration for throttling behavior

Since: 7.0.0


stopListening()

stopListening() => Promise<void>

Stop listening for compass heading changes. This stops the compass sensors and stops emitting events.

Since: 7.0.0


addListener('headingChange', ...)

addListener(eventName: 'headingChange', listenerFunc: (event: HeadingChangeEvent) => void) => Promise<{ remove: () => Promise<void>; }>

Add a listener for compass heading change events.

ParamTypeDescription
eventName'headingChange'- The event to listen for ('headingChange')
listenerFunc(event: HeadingChangeEvent) => void- The function to call when the event is emitted

Returns: Promise<{ remove: () => Promise<void>; }>

Since: 7.0.0


addListener('accuracyChange', ...)

addListener(eventName: 'accuracyChange', listenerFunc: (event: AccuracyChangeEvent) => void) => Promise<{ remove: () => Promise<void>; }>

Add a listener for compass accuracy change events. Only supported on Android. On iOS and Web, this will never emit events.

ParamTypeDescription
eventName'accuracyChange'- The event to listen for ('accuracyChange')
listenerFunc(event: AccuracyChangeEvent) => void- The function to call when the event is emitted

Returns: Promise<{ remove: () => Promise<void>; }>

Since: 8.2.0


removeAllListeners()

removeAllListeners() => Promise<void>

Remove all listeners for this plugin.

Since: 7.0.0


checkPermissions()

checkPermissions() => Promise<PermissionStatus>

Check the current permission status for accessing compass data. On iOS, this checks location permission status. On Android, this always returns 'granted' as no permissions are required.

Returns: Promise<PermissionStatus>

Since: 7.0.0


requestPermissions()

requestPermissions() => Promise<PermissionStatus>

Request permission to access compass data. On iOS, this requests location permission (required for heading data). On Android, this resolves immediately as no permissions are required.

Returns: Promise<PermissionStatus>

Since: 7.0.0


watchAccuracy()

watchAccuracy() => Promise<void>

Start monitoring compass accuracy. On Android, this monitors the magnetometer accuracy and emits accuracyChange events. Developers can listen to these events and implement their own UI for calibration prompts. On iOS and Web, this method does nothing as compass accuracy monitoring is not available.

Since: 8.2.0


unwatchAccuracy()

unwatchAccuracy() => Promise<void>

Stop monitoring compass accuracy. This stops the accuracy monitoring.

Since: 8.2.0


getAccuracy()

getAccuracy() => Promise<{ accuracy: CompassAccuracy; }>

Get the current compass accuracy level. On Android, returns the current magnetometer sensor accuracy. On iOS and Web, always returns CompassAccuracy.UNKNOWN as accuracy monitoring is not available.

Returns: Promise<{ accuracy: CompassAccuracy; }>

Since: 8.2.0


Interfaces

CompassHeading

Result containing the compass heading value.

PropTypeDescription
valuenumberCompass heading in degrees (0-360)

ListeningOptions

Options for configuring compass listening behavior.

PropTypeDescriptionDefaultSince
minIntervalnumberMinimum interval between heading change events in milliseconds. Lower values = more frequent updates but higher CPU/battery usage.1008.1.4
minHeadingChangenumberMinimum heading change in degrees required to trigger an event. Lower values = more sensitive but more events. Handles wraparound (e.g., 359° to 1° = 2° change).2.08.1.4

HeadingChangeEvent

Event data for heading change events.

PropTypeDescription
valuenumberCompass heading in degrees (0-360)

AccuracyChangeEvent

Event data for accuracy change events.

PropTypeDescription
accuracyCompassAccuracyCurrent accuracy level of the compass

PermissionStatus

Permission status for compass plugin.

PropTypeDescriptionSince
compassPermissionStatePermission state for accessing compass/location data. On iOS, this requires location permission to access heading. On Android, no special permissions are required for compass sensors.7.0.0

Type Aliases

PermissionState

'prompt' | 'prompt-with-rationale' | 'granted' | 'denied'

Enums

CompassAccuracy

MembersValueDescription
HIGH3High accuracy - approximates to less than 5 degrees of error
MEDIUM2Medium accuracy - approximates to less than 10 degrees of error
LOW1Low accuracy - approximates to less than 15 degrees of error
UNRELIABLE0Unreliable accuracy - approximates to more than 15 degrees of error
UNKNOWN-1Unknown accuracy value

Credits

This plugin is inspired by capacitor-native-compass by HeyItsBATMAN.

版本与发布记录

@capgo/capacitor-compass 共发布 28 个版本,首次发布于 2025/11/29;过去 12 个月发布了 28 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
8.1.24latest2026/10/1525 天前
8.1.232026/10/1327 天前
8.1.222026/10/091 个月前
8.1.212026/10/081 个月前
8.1.202026/09/161 个月前
8.1.192026/08/202 个月前

关于 @capgo/capacitor-compass 的常见问题

@capgo/capacitor-compass 是什么?

Native compass heading plugin for Capacitor

如何安装 @capgo/capacitor-compass?

在项目目录运行 npm install @capgo/capacitor-compass,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@capacitor/core(>=8.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@capgo/capacitor-compass 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@capgo/capacitor-compass 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@capgo/capacitor-compass 可以商用吗?

@capgo/capacitor-compass 使用 MPL-2.0 许可。弱 Copyleft:可以商用,也可以和闭源代码一起使用;但如果分发时修改了 MPL 授权的文件,这些文件的修改需以 MPL 开源。以上为概括,不构成法律意见,请以许可原文为准。

@capgo/capacitor-compass 的下载量有多少?

根据 npm 官方下载统计,@capgo/capacitor-compass 在 2026/10/09 – 2026/11/07 这 30 天内被下载 45,704 次,日均约 1,523 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@capgo/capacitor-compass 还在维护吗?

最新版本 8.1.24 发布于 2026/10/15(25 天前);至今共发布 28 个版本,其中过去 12 个月发布了 28 个;首次发布于 2025/11/29。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。