Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 78 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,16 +52,61 @@ Read about [Setting Permissions](https://capacitorjs.com/docs/android/configurat

## Location Button

Importing `@capacitor/geolocation` registers `<os-location-button>`. The plugin
Importing `@capacitor/geolocation` registers `<os-location-button>` on Android. The plugin
includes the Native Islands runtime, so applications do not install it separately.

The element shows the system location button on Android 17 and later, and Google's
compatibility button on older versions. On iOS and web it renders nothing. Use
[`getLocationButtonState()`](#getlocationbuttonstate) to show your own control where it is
`unavailable`:

```html
<os-location-button text-type="use-precise-location"></os-location-button>
<os-location-button id="location-button"></os-location-button>
```

```ts
const { state } = await Geolocation.getLocationButtonState();
if (state === 'unavailable') {
// Show your own control.
}

const button = document.querySelector('#location-button');
button.addEventListener('location-grant', (event) => console.log(event.detail.granted));
button.addEventListener('location-position', (event) => console.log(event.detail.coords));
button.addEventListener('location-error', (event) => console.log(event.detail.code, event.detail.reason));
```

Attributes: `text-type` (`use-precise-location` by default, or `share-precise-location`,
`near-my-precise-location`, `near-your-precise-location`, `precise-location`, `none`), `timeout`
(10000 ms), `maximum-age` (0 ms) and `enable-location-fallback` (`true`). The system translates
the label, so it can differ from your app's language.
Comment thread
ItsChaceD marked this conversation as resolved.
Resolved

Google Play requires apps that target Android 17 (API 37) to use the location button for one-time
precise location, or to submit a declaration explaining why it isn't enough. See
[Google Play's location permissions policy](https://support.google.com/googleplay/android-developer/answer/17033915).
Below Android 17 there is no system button and the `onlyForLocationButton` flag below is ignored, so
the plugin's other methods can still get precise location. There, the compatibility button is
optional: when `getLocationButtonState()` returns `compat`, you can show your own control instead.

To grant precise location only through the button, keep `ACCESS_COARSE_LOCATION` and declare
`ACCESS_FINE_LOCATION` with the `onlyForLocationButton` flag:

```xml
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"
android:usesPermissionFlags="onlyForLocationButton" />
```

On Android, the element renders a native button and emits `location-grant`,
`location-position`, and `location-error` DOM events. Browsers use
`navigator.geolocation`. Native iOS support is not currently provided.
With this flag, on Android 17 and later, your app gets precise location only through the button.
The rest of the plugin works with approximate location:

- When `requestPermissions()`, `getCurrentPosition()` or `watchPosition()` ask for permission, the
system dialog only offers approximate location.
- `getCurrentPosition()` and `watchPosition()` return approximate positions.
- `checkPermissions()` returns `location: 'denied'` and `coarseLocation: 'granted'`.

Once the user taps the button and allows precise location, the rest of the plugin also gets precise
location until the app is closed.

Style the element with ordinary CSS. The icon can inherit `color` or use its
component-specific custom property:
Expand All @@ -79,7 +124,8 @@ os-location-button {
```

The native button supports opaque hexadecimal and RGB colors. Border width supports
`0px` through `3px`; the corner radius supports `0px` through `68px`.
`0px` through `3px`; the corner radius supports `0px` through `68px`. Android draws no button
smaller than 48 by 48 pixels.

## API

Expand All @@ -90,6 +136,7 @@ The native button supports opaque hexadecimal and RGB colors. Border width suppo
* [`clearWatch(...)`](#clearwatch)
* [`checkPermissions()`](#checkpermissions)
* [`requestPermissions(...)`](#requestpermissions)
* [`getLocationButtonState()`](#getlocationbuttonstate)
* [Interfaces](#interfaces)
* [Type Aliases](#type-aliases)

Expand Down Expand Up @@ -193,6 +240,24 @@ Not available on web.
--------------------


### getLocationButtonState()

```typescript
getLocationButtonState() => Promise<LocationButtonState>
```

Check which location button this device supports.

The button is Android only. Use this to show your own control where it is `unavailable`, or to
hide the `compat` button on older Android versions.

**Returns:** <code>Promise&lt;<a href="#locationbuttonstate">LocationButtonState</a>&gt;</code>

**Since:** 9.0.0

--------------------


### Interfaces


Expand Down Expand Up @@ -238,6 +303,13 @@ Not available on web.
| **`permissions`** | <code>GeolocationPermissionType[]</code> |


#### LocationButtonState

| Prop | Type | Description | Since |
| ----------- | -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
| **`state`** | <code>'system' \| 'compat' \| 'unavailable'</code> | `system` on Android 17 and later, where the system draws the button. `compat` on older Android versions, which show Google's compatibility button. `unavailable` on iOS and web, where the `os-location-button` element renders nothing. | 9.0.0 |


### Type Aliases


Expand Down
Binary file modified android/libs/IONGeolocationLib-debug.aar
Binary file not shown.
Binary file modified android/libs/ionnativeislands-android-release.aar
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -85,17 +85,13 @@ class GeolocationPlugin : Plugin() {
}
}

/** Native Islands carrier methods hosted by Geolocation. */
@PluginMethod
fun nativeIslandsLocationButtonCapabilities(call: PluginCall) {
call.resolve(
JSObject().put(
"requiresUnobscuredSurface",
IONGLOCLocationButtonRegistry.requiresUnobscuredSurface(),
),
)
fun getLocationButtonState(call: PluginCall) {
val state = if (IONGLOCLocationButtonRegistry.requiresUnobscuredSurface()) "system" else "compat"
call.resolve(JSObject().put("state", state))
}

/** Native Islands carrier methods hosted by Geolocation. */
@PluginMethod
fun nativeIslandsApplyLayout(call: PluginCall) {
nativeIslandsController.submitLayout(call.data, failure = { code, message -> call.reject(message, code) }) {
Expand Down

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not needed to be done in this PR, but I might do after this PR is merged -> We probably don't need the iOS version of the app anymore. I mean what it would verify is that the button doesn't render, but don't think that's really worth it having 10 or 20 more files in the "final" PR. We can at least check that it doesn't appear on web, which is good enough for me.

But let me know if you agree / disagree. Might be thinking too much about small stuff here 😅

Maybe checking the visibility on iOS / web could be covered by a quick test?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it is ok to remove. We can probably just add a test that getLocationButtonState() returns unavailable on those platforms

Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"
android:usesPermissionFlags="onlyForLocationButton" />

<application
android:allowBackup="true"
Expand Down
66 changes: 57 additions & 9 deletions example-app-location-button/src/js/capacitor-welcome.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,13 +101,12 @@ window.customElements.define(
</capacitor-welcome-titlebar>
<main>
<p>
Renders the system LocationButton on Android 17+ (compileSdk 37), falling back to an
AppCompat replica below that. Tapping requests precise location directly — no
separate permission step. On grant, <code>fetchPosition()</code> delegates to the same
<code>IONGLOCController.getCurrentPosition()</code> used by the regular API below.
Android only: the system location button on Android 17 and later, Google's compat
button before that, and nothing on iOS and web.
</p>

<h2>os-location-button</h2>
<p>getLocationButtonState(): <code id="lb-state">…</code></p>
<os-location-button text-type="use-precise-location" style="display: block; margin: 10px 0;"></os-location-button>

<details id="location-button-customize">
Expand Down Expand Up @@ -163,15 +162,15 @@ window.customElements.define(
</div>
<div class="field field-inline">
<input type="checkbox" id="lb-enable-location-fallback" checked>
<label for="lb-enable-location-fallback">Enable location fallback (Android only — no effect on iOS)</label>
<label for="lb-enable-location-fallback">Enable location fallback</label>
</div>

<hr>

<h4>Layout (app-level CSS — not a plugin feature)</h4>
<div class="field field-inline">
<input type="checkbox" id="lb-width-auto" checked>
<label for="lb-width-auto">Auto width (plugin default: min(100%, 22rem))</label>
<label for="lb-width-auto">Auto width (plugin default: 100%)</label>
</div>
<div class="field">
<label for="lb-width">Width: <span id="lb-width-value">-</span>px</label>
Expand All @@ -182,7 +181,7 @@ window.customElements.define(
<label for="lb-height-auto">Auto height (plugin default: 3.25rem)</label>
</div>
<div class="field">
<label for="lb-height">Height: <span id="lb-height-value">-</span>px (above 136 shows the dead-zone gap on native api37 only — the LocationButton widget caps at 136dp inside a taller host; the web fallback has no such cap and just grows)</label>
<label for="lb-height">Height: <span id="lb-height-value">-</span>px (above 136 shows the dead-zone gap on api37 only: the LocationButton widget caps at 136dp inside a taller host)</label>
<input type="range" id="lb-height" min="40" max="200" value="52" disabled>
</div>
<div class="field">
Expand Down Expand Up @@ -213,6 +212,29 @@ window.customElements.define(
<h3>Result:</h3>
<pre id="current-location-result"></pre>
</div>

<hr>

<h2>Permissions</h2>
<p>
<code>checkPermissions()</code> and <code>requestPermissions()</code> from the plugin's normal JS API.
<code>coarseLocation</code> asks for ACCESS_COARSE_LOCATION only; <code>location</code> asks for
coarse and fine.
</p>
<p>
<button id="check-permissions" class="button">Check permissions</button>
</p>
<p>
<button id="request-permissions-coarse" class="button">Request coarse</button>
</p>
<p>
<button id="request-permissions-coarse-fine" class="button">Request coarse + fine</button>
</p>

<div id="permissions-result-container">
<h3>Result:</h3>
<pre id="permissions-result"></pre>
</div>
</main>
</div>
`;
Expand All @@ -222,6 +244,9 @@ window.customElements.define(
const self = this;

const locationButton = self.shadowRoot.querySelector('os-location-button');
Geolocation.getLocationButtonState().then(({ state }) => {
self.shadowRoot.querySelector('#lb-state').textContent = state;
});
const locationButtonEventsList = self.shadowRoot.querySelector('#location-button-events-list');

function logLocationButtonEvent(text) {
Expand Down Expand Up @@ -318,8 +343,6 @@ window.customElements.define(
});

// Fetch option controls — each maps to a real plugin-supported HTML attribute.
// `timeout`/`maximum-age` apply on every platform; `enable-location-fallback` is Android-only
// (silently ignored on iOS/web, per the regular getCurrentPosition() API it delegates to).
bindRange('lb-timeout', 'lb-timeout-value', (value) => {
locationButton.setAttribute('timeout', value);
});
Expand Down Expand Up @@ -382,6 +405,31 @@ window.customElements.define(
resultElement.textContent = `Error: code=${exception.code} message="${exception.message}"`;
}
});

const permissionsResult = self.shadowRoot.querySelector('#permissions-result');

async function showPermissions(label, action) {
try {
const status = await action();
permissionsResult.textContent = `${label}:\n${JSON.stringify(status, null, 2)}`;
} catch (exception) {
permissionsResult.textContent = `${label} error: code=${exception.code} message="${exception.message}"`;
}
}

self.shadowRoot.querySelector('#check-permissions').addEventListener('click', () => {
showPermissions('checkPermissions()', () => Geolocation.checkPermissions());
});
self.shadowRoot.querySelector('#request-permissions-coarse').addEventListener('click', () => {
showPermissions("requestPermissions({ permissions: ['coarseLocation'] })", () =>
Geolocation.requestPermissions({ permissions: ['coarseLocation'] }),
);
});
self.shadowRoot.querySelector('#request-permissions-coarse-fine').addEventListener('click', () => {
showPermissions("requestPermissions({ permissions: ['location'] })", () =>
Geolocation.requestPermissions({ permissions: ['location'] }),
);
});
}
},
);
Expand Down
7 changes: 6 additions & 1 deletion ios/Sources/GeolocationPlugin/GeolocationPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ public class GeolocationPlugin: CAPPlugin, CAPBridgedPlugin {
.init(name: "watchPosition", returnType: CAPPluginReturnCallback),
.init(name: "clearWatch", returnType: CAPPluginReturnPromise),
.init(name: "checkPermissions", returnType: CAPPluginReturnPromise),
.init(name: "requestPermissions", returnType: CAPPluginReturnPromise)
.init(name: "requestPermissions", returnType: CAPPluginReturnPromise),
.init(name: "getLocationButtonState", returnType: CAPPluginReturnPromise)
]

private var locationService: (any IONGLOCService)?
Expand Down Expand Up @@ -113,6 +114,10 @@ public class GeolocationPlugin: CAPPlugin, CAPBridgedPlugin {
checkPermissions(call)
}
}

@objc func getLocationButtonState(_ call: CAPPluginCall) {
call.resolve(["state": "unavailable"])
}
}

private extension GeolocationPlugin {
Expand Down
23 changes: 23 additions & 0 deletions src/definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,29 @@ export interface GeolocationPlugin {
* @since 1.0.0
*/
requestPermissions(permissions?: GeolocationPluginPermissions): Promise<PermissionStatus>;

/**
* Check which location button this device supports.
*
* The button is Android only. Use this to show your own control where it is `unavailable`, or to
* hide the `compat` button on older Android versions.
*
* @since 9.0.0
*/
getLocationButtonState(): Promise<LocationButtonState>;
}

export interface LocationButtonState {
/**
* `system` on Android 17 and later, where the system draws the button.
*
* `compat` on older Android versions, which show Google's compatibility button.
Comment thread
OS-pedrogustavobilro marked this conversation as resolved.
Resolved
*
* `unavailable` on iOS and web, where the `os-location-button` element renders nothing.
*
* @since 9.0.0
*/
state: 'system' | 'compat' | 'unavailable';
}

export interface ClearWatchOptions {
Expand Down
Loading