Flutter地理位置获取插件geopointer的使用

Flutter地理位置获取插件geopointer的使用

geopointer 是一个轻量级的Flutter库,用于常见的经纬度计算。

开始使用

这个库支持两种算法:“Haversine” 和 “Vincenty”。
“Haversine” 算法稍快一些,而 “Vincenty” 算法则更准确。

基本用法

GDistance
final GDistance distance = new GDistance();

// 计算两个坐标之间的距离(单位:千米)
// 结果为 423 千米
final int km = distance.as(LengthUnit.Kilometer,
 new GeoLatLng(52.518611,13.408056),new GeoLatLng(51.519475,7.46694444));

// 计算两个坐标之间的距离(单位:米)
// 结果为 422591.551 米
final int meter = distance(
 new GeoLatLng(52.518611,13.408056),
 new GeoLatLng(51.519475,7.46694444)
 );
Offset
final GDistance distance = const GDistance();
final num distanceInMeter = (EARTH_RADIUS * math.PI / 4).round();

final p1 = new GeoLatLng(0.0, 0.0);
final p2 = distance.offset(p1, distanceInMeter, 180);

// 输出:GeoLatLng(latitude:-45.219848, longitude:0.0)
print(p2.round());

// 输出:45° 13' 11.45" S, 0° 0' 0.00" O
print(p2.toSexagesimal());
GeoPath 平滑处理
// coordinates 是一个坐标列表
final GeoPath path = new GeoPath.from(coordinates);

// 结果是平滑后的路径
final GeoPath steps = path.equalize(8, smoothPath: true);

完整示例代码

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:geopointer/geopointer.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';

  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();
  }

  // 异步方法初始化平台状态
  Future<void> initPlatformState() async {
    String platformVersion;
    // 可能会失败,所以我们使用异步的 PlatformException。
    // 我们还处理了消息可能返回null的情况。
    try {
      platformVersion = await Geopointer.platformVersion ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // 如果在异步平台消息飞行时小部件被从树中移除,我们希望丢弃回复而不是调用
    // setState 来更新我们的不存在的外观。
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('插件示例应用'),
        ),
        body: Center(
          child: Text('运行在: $_platformVersion\n'),
        ),
      ),
    );
  }
}

更多关于Flutter地理位置获取插件geopointer的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter地理位置获取插件geopointer的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在 Flutter 中,geolocator 是一个常用的插件,用于获取设备的地理位置信息。它提供了丰富的功能,包括获取当前位置、监听位置变化、获取位置权限等。以下是如何使用 geolocator 插件的基本步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 geolocator 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  geolocator: ^10.0.0

然后运行 flutter pub get 来安装依赖。

2. 配置权限

为了获取地理位置,你需要在 AndroidManifest.xmlInfo.plist 文件中添加相应的权限配置。

Android

android/app/src/main/AndroidManifest.xml 文件中添加以下权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

iOS

ios/Runner/Info.plist 文件中添加以下权限:

<key>NSLocationWhenInUseUsageDescription</key>
<string>We need your location to provide better service.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>We need your location to provide better service.</string>

3. 获取当前位置

以下是一个简单的示例,展示了如何使用 geolocator 获取设备的当前位置:

import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: LocationScreen(),
    );
  }
}

class LocationScreen extends StatefulWidget {
  @override
  _LocationScreenState createState() => _LocationScreenState();
}

class _LocationScreenState extends State<LocationScreen> {
  Position? _currentPosition;

  Future<void> _getCurrentLocation() async {
    // 检查位置服务是否启用
    bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      // 位置服务未启用,提示用户启用
      return;
    }

    // 检查位置权限
    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        // 权限被拒绝,提示用户
        return;
      }
    }

    if (permission == LocationPermission.deniedForever) {
      // 权限被永久拒绝,提示用户
      return;
    }

    // 获取当前位置
    Position position = await Geolocator.getCurrentPosition(
      desiredAccuracy: LocationAccuracy.high,
    );

    setState(() {
      _currentPosition = position;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Geolocator Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            if (_currentPosition != null)
              Text(
                'Latitude: ${_currentPosition!.latitude}, Longitude: ${_currentPosition!.longitude}',
              ),
            ElevatedButton(
              onPressed: _getCurrentLocation,
              child: Text('Get Location'),
            ),
          ],
        ),
      ),
    );
  }
}

4. 监听位置变化

如果你需要监听位置的变化,可以使用 Geolocator.getPositionStream 方法:

StreamSubscription<Position>? _positionStreamSubscription;

void _startListening() {
  _positionStreamSubscription = Geolocator.getPositionStream(
    desiredAccuracy: LocationAccuracy.high,
    distanceFilter: 10, // 位置变化超过10米时触发
  ).listen((Position position) {
    setState(() {
      _currentPosition = position;
    });
  });
}

void _stopListening() {
  _positionStreamSubscription?.cancel();
}
回到顶部