43 lines
1.3 KiB
Dart
43 lines
1.3 KiB
Dart
import 'package:geolocator/geolocator.dart';
|
|
|
|
class LocationPoint {
|
|
const LocationPoint({
|
|
required this.longitude,
|
|
required this.latitude,
|
|
required this.accuracy,
|
|
required this.occurredAt,
|
|
});
|
|
|
|
final String longitude;
|
|
final String latitude;
|
|
final String accuracy;
|
|
final DateTime occurredAt;
|
|
}
|
|
|
|
abstract interface class LocationService {
|
|
Future<LocationPoint> current();
|
|
}
|
|
|
|
class GeolocatorLocationService implements LocationService {
|
|
@override
|
|
Future<LocationPoint> current() async {
|
|
if (!await Geolocator.isLocationServiceEnabled()) {
|
|
throw StateError('请先开启系统定位服务');
|
|
}
|
|
var permission = await Geolocator.checkPermission();
|
|
if (permission == LocationPermission.denied) {
|
|
permission = await Geolocator.requestPermission();
|
|
}
|
|
if (permission == LocationPermission.denied || permission == LocationPermission.deniedForever) {
|
|
throw StateError('定位权限未授权,无法完成该在线动作');
|
|
}
|
|
final position = await Geolocator.getCurrentPosition();
|
|
return LocationPoint(
|
|
longitude: position.longitude.toStringAsFixed(7),
|
|
latitude: position.latitude.toStringAsFixed(7),
|
|
accuracy: position.accuracy.toStringAsFixed(1),
|
|
occurredAt: position.timestamp,
|
|
);
|
|
}
|
|
}
|