Skip to content
Open
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
55 changes: 50 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,16 +52,35 @@ 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.

```html
<os-location-button text-type="use-precise-location"></os-location-button>
```
Comment on lines -55 to 60

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.

If this is documentation to show users how to declare the location button, it seems a bit confusing.


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.
The element shows the system location button on Android 17 and later, and Google's
compatibility button on older versions. It emits `location-grant`, `location-position`, and
`location-error` DOM events. On iOS and web it renders nothing. Call
[`getLocationButtonState()`](#getlocationbuttonstate) to hide the button or show your own control.

Attributes: `text-type` (`use-precise-location` by default, or `share-precise-location`,
`near-my-precise-location`, `near-your-precise-location`, `precise-location`, `none`), `timeout`
(5000 ms), `maximum-age` (3000 ms) and `enable-location-fallback` (`true`). The system translates
the label, so it can differ from your app's language.
Comment on lines +67 to +70

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.

Just a reminder that if you change the defaults in the TS code based on my other comment, change them here too.


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 17 and later, the regular API then gets approximate location until the button grants
precise location: after a request, `coarseLocation` is `granted` and `location` is `denied`. Older
versions ignore the flag.
Comment on lines +81 to +83

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.

It wasn't clear to me initially that "regular API" included request/check permissions and getting actual position.

Added some code to the example app here to validate that it's just that.

Maybe this phrase could be made a bit clearer?


Style the element with ordinary CSS. The icon can inherit `color` or use its
component-specific custom property:
Expand All @@ -79,7 +98,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 +110,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 +214,23 @@ Not available on web.
--------------------


### getLocationButtonState()

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

Check which location button this device supports.

The button is Android only. Use this to hide it, or to show your own control instead.

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

**Since:** 9.0.0

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


### Interfaces


Expand Down Expand Up @@ -238,6 +276,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?

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
74 changes: 61 additions & 13 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 @@ -154,24 +153,24 @@ window.customElements.define(

<h4>Fetch options (plugin properties)</h4>
<div class="field">
<label for="lb-timeout">Timeout: <span id="lb-timeout-value">10000</span>ms</label>
<input type="range" id="lb-timeout" min="1" max="60000" step="500" value="10000">
<label for="lb-timeout">Timeout: <span id="lb-timeout-value">5000</span>ms</label>
<input type="range" id="lb-timeout" min="1" max="60000" step="500" value="5000">
</div>
<div class="field">
<label for="lb-maximum-age">Maximum age: <span id="lb-maximum-age-value">0</span>ms</label>
<input type="range" id="lb-maximum-age" min="0" max="600000" step="1000" value="0">
<label for="lb-maximum-age">Maximum age: <span id="lb-maximum-age-value">3000</span>ms</label>
<input type="range" id="lb-maximum-age" min="0" max="600000" step="1000" value="3000">
</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
22 changes: 22 additions & 0 deletions src/definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,28 @@ 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 hide it, or to show your own control instead.

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.

"Use this to hide it" seems misleading, because it's not shown outside of Android.

Is there any visual difference from hiding it based on getLocationButtonState as opposed to how it already hides? Or it's more to not have the element declared in the first place?

*
* @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 on lines +91 to +93

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.

Worth making the distinction that to comply with google play's location button requirements, you technically only need to use <os-location-button for system, not compat?

Although, maybe that's better served in the plugin documentation in README rather than API. And it doesn't need to be done in this PR necessarily, as I said before, we can touch up the docs after this PR is merged, before opening the "general" PR to next.

*
* `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