美文网首页
flutter3.0开发—集成高德地图(待完善)

flutter3.0开发—集成高德地图(待完善)

作者: 码农界四爷__King | 来源:发表于2022-12-27 08:04 被阅读0次

首先登录高德地图 控制台
然后选择创建新应用 里面的应用名称和应用类型根据自己的项目填写

image.png

然后点击新建之后 选择右上角添加 里面的key名称根据项目名称填写
PackageName 则在AndroidManifest.xml文件里面


image.png image.png

接下来如何获取到高德地图的SHA1

在获取SHA1之前需要先把项目进行打包 打包过程中会产生一个****.jks文件

找到你的javaJDK安装路径 然后直接在命令窗口进入该目录,并且进入该目录的bin目录

然后再次执行命令:keytool -list -v -keystore D:\xxxx.jks

C:\Program Files\Java\jdk-11.0.14\bin>keytool -list -v -keystore D:\me\demo1.jks

输入jks的秘钥口令就可以了

111.png

获取到SHA1口令之后复制到对应的地方 然后点击提交可以


image.png

接下里集成高德地图

首先集成插件 amap_flutter_location 网址 https://pub.dev/packages/amap_flutter_location/versions

image.png
dependencies:
  amap_flutter_location: ^3.0.0

接下来配置一下相关信息 在android下的app里面的build.gradle 加上如下代码

implementation('com.amap.api:location:5.2.0')
image.png

然后在android对象里面加入以下代码

image.png image.png
signingConfigs {
        release { //发布版本的签名配置
            storeFile file('demo1.jks')
            keyAlias "key0"
            storePassword "1qaz2wsx"
            keyPassword "1qaz2wsx"
        }
        debug { //调试版本的签名配置
            storeFile file('demo1.jks')
            keyAlias "key0"
            storePassword "1qaz2wsx"
            keyPassword "1qaz2wsx"
        }
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }

        debug {
        // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. 
        signingConfig signingConfigs.debug
        }
    }

接下来在AndroidManifest.xml中配置相关代码

image.png
<!--访问网络-->
    <uses-permission android:name="android.permission.INTERNET" />
    <!--粗略定位-->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <!--精确定位-->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <!--申请调用 A-GPS 模块-->
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <!--用于获取运营商信息,用于支持提供运营商信息相关的接口-->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!--用于访问 wifi 网络信息,wifi 信息会用于进行网络定位-->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <!--用于获取 wifi 的获取权限,wifi 信息会用来进行网络定位-->
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <!--用于读取手机当前的状态-->
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <!--用于写入缓存数据到扩展存储卡-->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

配置定位 Service

image.png
<!-- 配置定位 Service -->
<service android:name="com.amap.api.location.APSService"/>

新建amap.dart文件

import 'package:flutter/material.dart';

import 'dart:async';
// import 'dart:io';
import 'package:amap_flutter_location/amap_flutter_location.dart'; //高德地图的包
import 'package:amap_flutter_location/amap_location_option.dart'; //高德地图的包
import 'package:permission_handler/permission_handler.dart'; //检测权限的包 需要配置一下  https://pub.dev/packages/permission_handler/install   permission_handler: ^10.2.0

class Amap extends StatefulWidget {
  const Amap({super.key});

  @override
  State<Amap> createState() => _AmapState();
}

class _AmapState extends State<Amap> {
  String _latitude = ""; //纬度
  String _longitude = ""; //经度

  //获取数据
  // Map<String, Object> _locationResult;
  //监听定位
  late StreamSubscription<Map<String, Object>> _locationListener;
  //实例化插件
  final AMapFlutterLocation _locationPlugin = AMapFlutterLocation();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    /// 动态申请定位权限
    requestPermission();

    AMapFlutterLocation.setApiKey(
        "dd2e80f12b3a8253c04ebb5a904f0e5d", "ios ApiKey");

    // 注册定位结果监听
    _locationListener = _locationPlugin
        .onLocationChanged()
        .listen((Map<String, Object> result) {
      setState(() {
        print(result);
        print("-----");
        // _locationResult = result;
        _latitude = result["latitude"].toString();
        _longitude = result["longitude"].toString();
      });
    });
  }

  /// 动态申请定位权限
  void requestPermission() async {
    // 申请权限
    bool hasLocationPermission = await requestLocationPermission();
    if (hasLocationPermission) {
      print("定位权限申请通过");
    } else {
      print("定位权限申请不通过");
    }
  }

  ///  申请定位权限  授予定位权限返回true, 否则返回false
  Future<bool> requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;
    print('=====================');
    print(status);
    print(PermissionStatus.granted);
    print('=====================');
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.status;
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  ///开始定位
  void _startLocation() {
    if (null != _locationPlugin) {
      print('---------');
      print(_locationPlugin);
      print('---------');
      // ///开始定位之前设置定位参数
      _setLocationOption();
      _locationPlugin.startLocation();
    }
  }

  ///设置定位参数
  void _setLocationOption() {
    if (null != _locationPlugin) {
      AMapLocationOption locationOption = new AMapLocationOption();

      ///是否单次定位
      locationOption.onceLocation = false;

      ///是否需要返回逆地理信息
      locationOption.needAddress = true;

      ///逆地理信息的语言类型
      locationOption.geoLanguage = GeoLanguage.DEFAULT;

      locationOption.desiredLocationAccuracyAuthorizationMode =
          AMapLocationAccuracyAuthorizationMode.ReduceAccuracy;

      locationOption.fullAccuracyPurposeKey = "AMapLocationScene";

      ///设置Android端连续定位的定位间隔
      locationOption.locationInterval = 2000;

      ///设置Android端的定位模式<br>
      ///可选值:<br>
      ///<li>[AMapLocationMode.Battery_Saving]</li>
      ///<li>[AMapLocationMode.Device_Sensors]</li>
      ///<li>[AMapLocationMode.Hight_Accuracy]</li>
      locationOption.locationMode = AMapLocationMode.Hight_Accuracy;

      ///设置iOS端的定位最小更新距离<br>
      locationOption.distanceFilter = -1;

      ///设置iOS端期望的定位精度
      /// 可选值:<br>
      /// <li>[DesiredAccuracy.Best] 最高精度</li>
      /// <li>[DesiredAccuracy.BestForNavigation] 适用于导航场景的高精度 </li>
      /// <li>[DesiredAccuracy.NearestTenMeters] 10米 </li>
      /// <li>[DesiredAccuracy.Kilometer] 1000米</li>
      /// <li>[DesiredAccuracy.ThreeKilometers] 3000米</li>
      locationOption.desiredAccuracy = DesiredAccuracy.Best;

      ///设置iOS端是否允许系统暂停定位
      locationOption.pausesLocationUpdatesAutomatically = false;

      ///将定位参数设置给定位插件
      _locationPlugin.setLocationOption(locationOption);
    }
  }

  @override
  void dispose() {
    super.dispose();

    ///移除定位监听
    if (null != _locationListener) {
      _locationListener.cancel();
    }

    ///销毁定位
    if (null != _locationPlugin) {
      _locationPlugin.destroy();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('纬度:$_latitude'),
          Text('经度:$_longitude'),
          const SizedBox(
            height: 20,
          ),
          ElevatedButton(
              onPressed: () {
                print('开始定位');
                _startLocation();
              },
              child: const Text("开始定位"))
        ],
      ),
    );
  }
}

相关文章

网友评论

      本文标题:flutter3.0开发—集成高德地图(待完善)

      本文链接:https://www.haomeiwen.com/subject/lofgqdtx.html