The Geolocation API provides simple methods for getting and tracking the current position of the device using GPS, along with altitude, heading, and speed information if available.
Apple requires privacy descriptions to be specified in
Info.plist
for location information:
Name:
Privacy - Location Always Usage Description
Key:
NSLocationAlwaysUsageDescription
Name:
Privacy - Location When In Use Usage Description
Key:
NSLocationWhenInUseUsageDescription
Read about Setting iOS Permissions in the iOS Guide for more information on setting iOS permissions in Xcode
This API requires the following permissions be added to your
AndroidManifest.xml
:
<!-- Geolocation API -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
The first two permissions ask for location data, both fine and coarse, and the last line is optional but necessary if your app requires GPS to function. You may leave it out, though keep in mind that this may mean your app is installed on devices lacking GPS hardware.
Read about Setting Android Permissions in the Android Guide for more information on setting Android permissions.
import { Plugins } from '@capacitor/core';
const { Geolocation } = Plugins;
class GeolocationExample {
async getCurrentPosition() {
const coordinates = await Geolocation.getCurrentPosition();
console.log('Current', coordinates);
}
watchPosition() {
const wait = Geolocation.watchPosition({}, (position, err) => {});
}
}
getCurrentPosition(options?: GeolocationOptions) => Promise<GeolocationPosition>
Get the current GPS location of the device
Param | Type |
---|---|
options |
GeolocationOptions |
Returns:
Promise<GeolocationPosition>
watchPosition(options: GeolocationOptions, callback: GeolocationWatchCallback) => CallbackID
Set up a watch for location changes. Note that watching for location changes can consume a large amount of energy. Be smart about listening only when you need to.
Param | Type |
---|---|
options |
GeolocationOptions |
callback |
(position: GeolocationPosition, err?: any) => void |
Returns:
string
clearWatch(options: { id: string; }) => Promise<void>
Clear a given watch
Param | Type |
---|---|
options |
{ id: string; } |
Prop | Type | Description |
---|---|---|
timestamp |
number |
Creation timestamp for coords |
coords |
{ latitude: number; longitude: number; accuracy: number; altitudeAccuracy?: number; altitude?: number; speed?: number; heading?: number; } |
The GPS coordinates along with the accuracy of the data |
Prop | Type |
---|---|
enableHighAccuracy |
boolean |
timeout |
number |
maximumAge |
number |