Flutter高德地图定位插件amap_location_muka的使用

Flutter高德地图定位插件amap_location_muka的使用

Flutter 高德定位插件 amap_location_muka 提供了在 Flutter 应用中集成高德地图定位功能的能力。以下是详细的使用说明及完整示例。


引入方式

pubspec.yaml 文件中添加依赖:

dependencies:
  amap_location_muka: ^0.1.1

然后运行以下命令以安装依赖:

flutter pub get

IOS 配置

Info.plist 文件中添加以下配置:

<!-- 默认配置 -->
<key>NSLocationWhenInUseUsageDescription</key>
<string>App需要您的同意,才能访问位置</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>App需要您的同意,才能访问位置</string>

<!-- 导航或后台持续定位时需要额外配置 -->
<key>UIBackgroundModes</key>
<array>
    <string>location</string>
    <string>audio</string>
</array>

Web 配置

在 HTML 文件中引入高德地图脚本:

<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=你的key"></script>

功能支持

支持的功能:

  • ✅ 单次获取位置信息
  • ✅ 持续获取位置信息

不支持的功能:

  • ❌ 后台持续定位
  • ❌ 地理围栏

使用示例

以下是完整的示例代码,展示了如何使用 amap_location_muka 插件进行单次定位和持续定位。

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

import 'package:amap_location_muka/amap_location_muka.dart';
import 'package:permission_handler/permission_handler.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

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

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  Location? _location;
  Function? stopLocation;

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

    initPlatformState();
  }

  [@override](/user/override)
  void didChangeAppLifecycleState(AppLifecycleState state) async {
    switch (state) {
      case AppLifecycleState.inactive: // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
        break;
      case AppLifecycleState.resumed: // 应用程序可见,前台
        print('应用恢复到前台');
        await AMapLocation.disableBackground();
        break;
      case AppLifecycleState.paused: // 应用程序不可见,后台
        print('应用切换到后台');
        await AMapLocation.enableBackground(
          assetName: 'app_icon',
          label: '正在获取位置信息',
          title: '高德地图',
          vibrate: false,
        );
        break;
      default:
        break;
    }
  }

  // 初始化平台状态
  Future<void> initPlatformState() async {
    // 请求权限(仅限非 Web 平台)
    if (!kIsWeb) {
      await Permission.location.request();
    }

    // 更新隐私设置
    await AMapLocation.updatePrivacyShow(true, true);
    await AMapLocation.updatePrivacyAgree(true);

    // 设置高德地图 API Key
    await AMapLocation.setApiKey('androidKey', 'iosKey');

    // 单次定位
    _location = await AMapLocation.fetch();
    print(_location?.toJson());

    // 开始持续定位
    stopLocation = await AMapLocation.start(
      time: 1000, // 定位间隔时间(毫秒)
      listen: (Location location) {
        print(location.toJson());
      },
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('高德地图定位示例'),
        ),
        body: Column(
          children: <Widget>[
            Center(
              child: Text('当前位置: ${_location?.address ?? '未定位'}'),
            ),
            ElevatedButton(
              child: Text('停止定位'),
              onPressed: () async {
                if (stopLocation != null) {
                  await stopLocation!();
                  print('停止定位');
                }
              },
            ),
            ElevatedButton(
              child: Text('单次定位'),
              onPressed: () async {
                _location = await AMapLocation.fetch();
                print(_location?.toJson());
                print('单次定位完成');
                setState(() {});
              },
            ),
            ElevatedButton(
              child: Text('持续定位'),
              onPressed: () async {
                print('开始持续定位');
                stopLocation = await AMapLocation.start(
                  time: 1000,
                  listen: (Location location) {
                    print(location.toJson());
                  },
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}
1 回复

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


在 Flutter 中使用高德地图定位插件 amap_location_muka 可以帮助你获取设备的当前位置信息。以下是如何使用这个插件的详细步骤。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  amap_location_muka: ^0.2.0  # 请使用最新版本

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

2. 配置高德地图 SDK

在使用高德地图定位功能之前,你需要在高德开放平台上注册应用,并获取 AppKey

Android 配置

  1. android/app/src/main/AndroidManifest.xml 文件中添加以下配置:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <application
        android:name=".MyApplication"
        android:label="Your App"
        android:icon="@mipmap/ic_launcher">

        <!-- 高德地图 AppKey -->
        <meta-data
            android:name="com.amap.api.v2.apikey"
            android:value="your_amap_appkey" />

    </application>
</manifest>
  1. android/app/build.gradle 文件中,确保 minSdkVersion 至少为 16:
defaultConfig {
    applicationId "com.example.yourapp"
    minSdkVersion 16
    targetSdkVersion 30
    versionCode 1
    versionName "1.0"
}

iOS 配置

  1. ios/Runner/Info.plist 文件中添加以下配置:
<key>NSLocationWhenInUseUsageDescription</key>
<string>我们需要使用您的位置信息来提供更好的服务</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>我们需要使用您的位置信息来提供更好的服务</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>我们需要使用您的位置信息来提供更好的服务</string>
  1. ios/Runner/AppDelegate.swift 文件中添加以下代码:
import UIKit
import Flutter
import AMapLocationKit

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    AMapServices.shared()?.apiKey = "your_amap_appkey"
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

3. 使用插件获取位置信息

在你的 Flutter 代码中,你可以使用 amap_location_muka 插件来获取设备的位置信息。

import 'package:flutter/material.dart';
import 'package:amap_location_muka/amap_location.dart';

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

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

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

class _LocationScreenState extends State<LocationScreen> {
  String _locationInfo = 'Unknown';

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

  Future<void> _getLocation() async {
    try {
      AMapLocation location = await AMapLocationClient.getLocation();
      setState(() {
        _locationInfo = 'Latitude: ${location.latitude}, Longitude: ${location.longitude}';
      });
    } catch (e) {
      setState(() {
        _locationInfo = 'Failed to get location: $e';
      });
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Location Example'),
      ),
      body: Center(
        child: Text(_locationInfo),
      ),
    );
  }
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!