Flutter地图定位插件amap_location_fluttify的使用

发布于 1周前 作者 itying888 来自 Flutter

Flutter 地图定位插件 amap_location_fluttify 的使用

高德 定位组件

Dart 接口基于 fluttify 引擎生成。dartdoc 接口文档。

DEMO 与 社区

安装:

dependencies:
  flutter:
    sdk: flutter
  amap_location_fluttify: ^x.x.x

导入:

import 'package:amap_location_fluttify/amap_location_fluttify.dart';

使用:

/// 注意: 只要是返回 Future 的方法, 一律使用 `await` 修饰, 确保当前方法执行完成后再执行下一行, 在不能使用 `await` 修饰的环境下, 在 `then` 方法中执行下一步。
/// 初始化 iOS 在 init 方法中设置, Android 需要去 AndroidManifest.xml 里去设置, 详见 https://lbs.amap.com/api/android-sdk/gettingstarted
await AmapCore.init('ios key');

// 单次定位
if (await requestPermission()) {
  final location = await AmapLocation.fetchLocation();
  setState(() => _location = location);
}

// 连续定位
if (await requestPermission()) {
  AmapLocation.listenLocation()
    .listen((location) => setState(() => _location = location));
}

LICENSE

版权 © 2020 yohom

根据 Apache License, Version 2.0 许可证授权; 你可能无法使用此文件除非符合许可证的规定。 你可以在 http://www.apache.org/licenses/LICENSE-2.0 获取一份许可证的副本。

除非法律要求或以书面形式同意,否则软件将按“原样”分发,不附带任何明示或暗示的担保或条件。有关特定的语言管理许可和限制,请参阅许可证。


示例代码

import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await AmapLocation.instance.updatePrivacyShow(true);
  await AmapLocation.instance.updatePrivacyAgree(true);
  await AmapLocation.instance.init(iosKey: 'f6422eadda731fb0d9ffb3260a5cf899');
  runApp(MyApp());
}

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

class _MyAppState extends State<MyApp> {
  Location? _location;
  String? _fenceStatus;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Plugin example app')),
        body: Padding(
          padding: EdgeInsets.symmetric(horizontal: 16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ElevatedButton(
                onPressed: () async {
                  if (await requestPermission()) {
                    final location = await AmapLocation.instance.fetchLocation();
                    setState(() => _location = location);
                  }
                },
                child: Text('获取单次定位'),
              ),
              ElevatedButton(
                onPressed: () async {
                  if (await requestPermission()) {
                    await AmapLocation.instance.enableBackgroundLocation(
                      10,
                      BackgroundNotification(
                        contentTitle: 'contentTitle',
                        channelId: 'channelId',
                        contentText: 'contentText',
                        channelName: 'channelName',
                      ),
                    );
                    AmapLocation.instance
                        .listenLocation()
                        .listen((event) => setState(() => _location = event));
                  }
                },
                child: Text('获取连续定位'),
              ),
              ElevatedButton(
                onPressed: () async {
                  if (await requestPermission()) {
                    await AmapLocation.instance.stopLocation();
                    setState(() => _location = null);
                  }
                },
                child: Text('停止定位'),
              ),
              ElevatedButton(
                onPressed: () async {
                  if (await requestPermission()) {
                    AmapLocation.instance
                        .addCircleGeoFence(
                      center: LatLng(29, 119),
                      radius: 1000,
                      customId: 'testid',
                    )
                        .listen((event) {
                      setState(() {
                        _fenceStatus =
                            '状态: ${event.status}, 围栏id: ${event.fenceId}, 自定义id: ${event.customId}';
                      });
                    });
                  }
                },
                child: Text('添加圆形围栏'),
              ),
              ElevatedButton(
                onPressed: () async {
                  if (await requestPermission()) {
                    AmapLocation.instance.addPolygonGeoFence(
                      pointList: <LatLng>[
                        LatLng(29.255201, 119.353437),
                        LatLng(28.974455, 119.508619),
                        LatLng(29.172496, 119.560804),
                        LatLng(29.306707, 119.422101),
                      ],
                      customId: 'testid',
                    ).listen((event) {
                      setState(() {
                        _fenceStatus =
                            '状态: ${event.status}, 围栏id: ${event.fenceId}, 自定义id: ${event.customId}';
                      });
                    });
                  }
                },
                child: Text('添加多边形围栏'),
              ),
              ElevatedButton(
                onPressed: () async {
                  if (await requestPermission()) {
                    AmapLocation.instance
                        .addPoiGeoFence(
                      keyword: '肯德基',
                      customId: 'testid',
                      city: '兰溪',
                      aroundRadius: 10000,
                    )
                        .listen((event) {
                      setState(() {
                        _fenceStatus =
                            '状态: ${event.status}, 围栏id: ${event.fenceId}, 自定义id: ${event.customId}';
                      });
                    });
                  }
                },
                child: Text('添加poi围栏'),
              ),
              ElevatedButton(
                onPressed: () async {
                  if (await requestPermission()) {
                    AmapLocation.instance
                        .addDistrictGeoFence(keyword: '兰溪')
                        .listen((event) {
                      setState(() {
                        _fenceStatus =
                            '状态: ${event.status}, 围栏id: ${event.fenceId}, 自定义id: ${event.customId}';
                      });
                    });
                  }
                },
                child: Text('添加行政区划围栏'),
              ),
              ElevatedButton(
                onPressed: () {
                  AmapLocation.instance.dispose();
                },
                child: Text('释放资源'),
              ),
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      if (_location != null)
                        Center(
                          child: Text(
                            _location.toString(),
                            textAlign: TextAlign.center,
                          ),
                        ),
                      if (_fenceStatus != null)
                        Center(
                          child: Text(
                            _fenceStatus.toString(),
                            textAlign: TextAlign.center,
                          ),
                        ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Future<bool> requestPermission() async {
  final permissions = await Permission.locationWhenInUse.request();

  if (permissions.isGranted) {
    return true;
  } else {
    debugPrint('需要定位权限!');
    return false;
  }
}

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

1 回复

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


当然,以下是一个使用 amap_location_fluttify 插件在 Flutter 应用中实现地图定位的示例代码。这个插件是阿里云地图(高德地图)定位功能的 Flutter 包装器。

首先,确保在 pubspec.yaml 文件中添加依赖项:

dependencies:
  flutter:
    sdk: flutter
  amap_location_fluttify: ^x.y.z  # 请将 x.y.z 替换为最新版本号

然后,运行 flutter pub get 来获取依赖项。

接下来,配置 Android 和 iOS 项目以使用高德地图服务。这包括在 AndroidManifest.xml 和 Info.plist 中添加必要的权限和 API Key。

Android 配置

android/app/src/main/AndroidManifest.xml 中添加权限和 API Key:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <!-- 添加定位权限 -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <!-- 高德地图 API Key -->
    <application
        ... >
        <meta-data
            android:name="com.amap.api.v2.apikey"
            android:value="你的高德地图API_KEY"/>
        ...
    </application>
</manifest>

iOS 配置

ios/Runner/Info.plist 中添加权限:

<key>NSLocationWhenInUseUsageDescription</key>
<string>需要您的位置信息以显示地图和定位</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>需要您的位置信息以显示地图和定位</string>
<key>io.flutter.embedded_views_preview</key>
<true/>

并在 AppDelegate.swiftAppDelegate.m 中初始化高德地图 SDK(如果你使用的是 Swift):

import UIKit
import Flutter
import AMapFoundationKit

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    // 初始化高德地图 SDK
    AMapServices.shared().apiKey = "你的高德地图API_KEY"
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

Flutter 代码实现

接下来,在你的 Flutter 项目中实现定位功能。创建一个 Dart 文件(例如 main.dart),并编写以下代码:

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

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  AMapLocation? _location;

  @override
  void initState() {
    super.initState();
    _getLocation();
  }

  Future<void> _getLocation() async {
    AMapLocationClient client = AMapLocationClient(
      apiKey: '你的高德地图API_KEY',
      // 可以在这里配置其他参数,如定位模式、是否需要重新定位等
    );

    AMapLocationOption option = AMapLocationOption()
      ..onceLocation = true
      ..needAddress = true;

    client.startLocation(option).then((AMapLocationResult result) {
      if (result.code == 0) {
        setState(() {
          _location = result.locations?.first;
        });
      } else {
        print('定位失败,错误码:${result.code}');
      }
    }).catchError((e) {
      print('定位过程中发生错误:$e');
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('高德地图定位示例'),
        ),
        body: Center(
          child: _location == null
              ? CircularProgressIndicator()
              : Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text('经度:${_location!.longitude}'),
                    Text('纬度:${_location!.latitude}'),
                    Text('地址:${_location!.address ?? '未知地址'}'),
                  ],
                ),
        ),
      ),
    );
  }
}

以上代码创建了一个简单的 Flutter 应用,它使用 amap_location_fluttify 插件来获取当前位置,并在屏幕上显示经度、纬度和地址信息。

请确保替换 '你的高德地图API_KEY' 为你自己的高德地图 API Key。这个示例展示了如何初始化定位客户端、配置定位选项、启动定位,并在获取到位置信息后更新 UI。

回到顶部