location_handler.dart 1.25 KB
import 'package:appframe/services/dispatcher.dart';
import 'package:geolocator/geolocator.dart';

class LocationHandler extends MessageHandler {
  @override
  Future<dynamic> handleMessage(params) async {
    // if (params is! Map<String, dynamic>) {
    //   throw Exception('参数错误');
    // }
    //
    // var type = params['type'] as String?;
    // type = type ?? 'gcj02';

    GeolocatorPlatform geolocator = GeolocatorPlatform.instance;

    // 检查定位服务是否启用
    final serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      throw '定位服务未启用';
    }

    var permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        throw 'no auth';
      }
    }

    if (permission == LocationPermission.deniedForever) {
      throw 'no auth';
    }

    final pos = await geolocator.getCurrentPosition();
    return {
      'latitude': pos.latitude,
      'longitude': pos.longitude,
      'speed': pos.speed,
      'accuracy': pos.accuracy,
      'altitude': pos.altitude,
      'verticalAccuracy': 0,
      'horizontalAccuracy': 0,
    };
  }
}