地理定位 26.01
Geolocation 类提供了与浏览器的地理定位子系统的接口。使用它可以一次请求设备的当前位置,或者监视位置以获取持续更新。
设置和先决条件
地理定位 API 需要:
- 安全上下文 (HTTPS)。
localhost源是豁免的,可以在本地开发中通过 HTTP 工作。 - 用户位置访问权限。浏览器在第一次请求位置时会自动提示,并按来源持久化该选择。
当子系统不可用时,访问它将抛出 WebforjRuntimeException。
实例
获取当前环境的地理定位实例:
import com.webforj.geolocation.Geolocation;
Geolocation geo = Geolocation.getCurrent();
if (Geolocation.isPresent()) {
// ...
}
Geolocation.ifPresent(g -> {
// ...
});
请求位置
调用 getCurrentPosition() 来请求设备的当前地理位置。返回的 PendingResult 将与报告的 GeolocationPosition 完成,或者在浏览器无法获取位置时异常收到 WebforjGeolocationException。
PendingResult<GeolocationPosition> request = Geolocation.getCurrent().getCurrentPosition();
request.thenAccept(position -> {
double lat = position.getLatitude();
double lng = position.getLongitude();
double accuracy = position.getAccuracy();
});
request.exceptionally(throwable -> {
WebforjGeolocationException error = (WebforjGeolocationException) throwable;
GeolocationStatus status = error.getStatus();
String message = error.getMessage();
return null;
});
浏览器权限
浏览器可能会在第一次请求位置时提示用户获得权限。该提示由浏览器自身显示,并不属于应用 UI 的一部分。
监视位置
注册一个监视监听器,以接收设备移动时的位置更新流。
ListenerRegistration<GeolocationWatchEvent> registration =
Geolocation.getCurrent().onWatch(event -> {
if (event.isSuccess()) {
GeolocationPosition position = event.getPosition().orElseThrow();
// ...
} else {
GeolocationStatus status = event.getStatus();
String message = event.getMessage().orElse("");
}
});
// 后来,停止监视:
registration.remove();
每次更新,无论成功与否,都会触发一个 GeolocationWatchEvent。在读取位置之前,检查 isSuccess()。