地理位置
付费插件
此插件需要购买。价格:$49(一次性购买)
概述
Geolocation API 提供对设备 GPS 和位置服务的访问,以确定用户的当前位置。
安装
shell
composer require nativephp/mobile-geolocation使用
PHP (Livewire/Blade)
php
use Native\Mobile\Facades\Geolocation;
// 使用网络定位获取位置(更快,精度较低)
Geolocation::getCurrentPosition();
// 使用 GPS 获取位置(更慢,精度更高)
Geolocation::getCurrentPosition(true);
// 检查权限状态
Geolocation::checkPermissions();
// 请求权限
Geolocation::requestPermissions();JavaScript (Vue/React/Inertia)
js
import { geolocation, on, off, Events } from '#nativephp';
// 使用网络定位获取位置
await geolocation.getCurrentPosition();
// 使用 GPS 获取位置(高精度)
await geolocation.getCurrentPosition()
.fineAccuracy(true);
// 带有用于跟踪的标识符
await geolocation.getCurrentPosition()
.fineAccuracy(true)
.id('current-loc');
// 检查权限
await geolocation.checkPermissions();
// 请求权限
await geolocation.requestPermissions();事件
LocationReceived
当请求位置数据时触发(成功或失败)。
事件参数:
bool $success- 是否成功获取位置float $latitude- 纬度坐标(成功时)float $longitude- 经度坐标(成功时)float $accuracy- 精度(米)(成功时)int $timestamp- 位置修正的 Unix 时间戳string $provider- 使用的位置提供者(GPS、网络等)string $error- 错误消息(失败时)
php
use Native\Mobile\Attributes\OnNative;
use Native\Mobile\Events\Geolocation\LocationReceived;
#[OnNative(LocationReceived::class)]
public function handleLocationReceived(
$success = null,
$latitude = null,
$longitude = null,
$accuracy = null,
$timestamp = null,
$provider = null,
$error = null
) {
if ($success) {
// 使用位置数据
}
}js
import { on, off, Events } from '#nativephp';
import { ref, onMounted, onUnmounted } from 'vue';
const location = ref({ latitude: null, longitude: null });
const error = ref('');
const handleLocationReceived = (payload) => {
if (payload.success) {
location.value = {
latitude: payload.latitude,
longitude: payload.longitude
};
} else {
error.value = payload.error;
}
};
onMounted(() => {
on(Events.Geolocation.LocationReceived, handleLocationReceived);
});
onUnmounted(() => {
off(Events.Geolocation.LocationReceived, handleLocationReceived);
});PermissionCheckResult
当权限检查完成时触发。
可能的值:
'granted'- 权限已授予'denied'- 权限被拒绝'not_determined'- 权限尚未请求
PermissionRequestResult
当权限请求完成时触发。
特殊值:
'permanently_denied'- 用户永久拒绝了权限
隐私注意事项
- 解释原因 - 在请求之前说明为什么需要位置访问
- 在适当时机请求 - 当功能实际需要时
- 尊重拒绝 - 在可能的情况下提供替代功能
- 使用适当精度 - 如果粗略位置足够,不要请求精确位置
- 限制频率 - 不要频繁请求位置更新
性能注意事项
- 电池使用 - GPS 比网络定位更耗电
- 首次定位时间 - GPS 需要更长时间获取初始位置
- 室内精度 - GPS 在室内可能效果不佳
- 缓存 - 考虑缓存最近的位置以获得更好的用户体验