Android集成高德Flutter地图(三)定位

一、集成高德地图

我的项目是需要显示地图的,所以定位是在地图的基础上实现的,当然定位也可以单独实现,获取到位置相关各种信息

二、集成高德定位

①、集成定位基础SDK
在Flutter项目中Android文件夹下的build.gradle添加

implementation('com.amap.api:location:6.1.0')

注意兼容性处理
在这里插入图片描述
在这里插入图片描述

我这里集成的是Flutter3.0插件
所以配置build.gradle为:

dependencies {
    //高德地图Flutter插件内不包含基础SDK包,使用时请参考官网关于集成Android地图SDK和iOS地图SDK说明配置地图SDK
   // 高德地图Flutter插件3.0.0版本基于地图SDK8.1.0开发,适配高德地图SDK版本8.1.0及以上版本
    //高德定位Flutter插件3.0.0版本基于Android定位5.6.0和iOS定位2.8.0版本开发,适配Android定位5.6.0和iOS定位2.8.0及以上版本
//    implementation('com.amap.api:map2d:6.0.0')
    implementation('com.amap.api:3dmap:9.2.1')
    implementation('com.amap.api:location:6.1.0')
}

这里注意有可能会冲突:
文档生成日期的 定位location最新版本是6.1.0 ,3dmap的最新版本9.4.0,经测试发现location使用6.1.0,3dmap使用9.2.1以上版本时(不包括9.2.1)编译会报错:

Execution failed for task ':app:checkDebugDuplicateClasses'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.CheckDuplicatesRunnable
   > Duplicate class com.amap.api.fence.DistrictItem found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.fence.DistrictItem$1 found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.fence.GeoFence found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.fence.GeoFence$1 found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.fence.GeoFenceClient found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.fence.GeoFenceListener found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.fence.PoiItem found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.fence.PoiItem$1 found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.AMapLocation found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.AMapLocation$1 found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.AMapLocationClient found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.AMapLocationClientOption found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.AMapLocationClientOption$1 found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.AMapLocationClientOption$2 found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.AMapLocationClientOption$AMapLocationMode found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.AMapLocationClientOption$AMapLocationProtocol found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.AMapLocationClientOption$AMapLocationPurpose found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.AMapLocationClientOption$GeoLanguage found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.AMapLocationListener found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.AMapLocationQualityReport found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.APSService found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.CoordUtil found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.CoordinateConverter found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.CoordinateConverter$1 found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.CoordinateConverter$CoordType found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.DPoint found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.DPoint$1 found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.UmidtokenInfo found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.UmidtokenInfo$1 found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
     Duplicate class com.amap.api.location.UmidtokenInfo$a found in modules jetified-3dmap-9.4.0 (com.amap.api:3dmap:9.4.0) and jetified-location-6.1.0 (com.amap.api:location:6.1.0)
  • 解决办法:
    将3dmap使用8.1.0–9.2.1版本

②、定位权限动态申请

记得处理6.0以上系统的动态申请定位权限:
我这里使用插件:

```dart
permission_handler: 10.0.1
requestPermiss() async {
    Map<Permission, PermissionStatus> statuses = await [
      Permission.location,
      // Permission.storage,
      // Permission.camera,
    ].request();
    //验证权限是否授权
    var status = await Permission.location.status;

    if (status == PermissionStatus.granted) {
      LogUtil.d('定位权限:true');
      //已经授权
    } else {
      LogUtil.d('定位权限:false');
      //退出应用
      Future.value(true);
    }
  }

③、高德定位文档里面需要首先设置权限和key代码如下:

 StreamSubscription<Map<String, Object>>? _locationListener;

  AMapFlutterLocation _locationPlugin = new AMapFlutterLocation();
 

 
  void initState() {
    super.initState();
    initLocation();
  }
/*地

图定位*/
  void initLocation() {
    //高德定位
     AMapFlutterLocation.updatePrivacyShow(true, true);
     AMapFlutterLocation.updatePrivacyAgree(true);
    AMapFlutterLocation.setApiKey(
        "8c278373b54c9c393c74f1d1a2d31d49", "ios ApiKey");
    ///iOS 获取native精度类型
    if (Platform.isIOS) {
      requestAccuracyAuthorization();
    }
    ///注册定位结果监听
    _locationListener = _locationPlugin
        .onLocationChanged()
        .listen((Map<String, Object> result) {
      setState(() {
        _locationResult = result;
        LogUtils.e("高德定位==========="+result.toString());
        LogUtils.e("高德定位latitude==========="+result['latitude'].toString());
        LogUtils.e("高德定位longitude: ==========="+result['longitude'].toString());
        LogUtils.e("高德定位country: ==========="+result['country'].toString());
        LogUtils.e("高德定位province: ==========="+result['province'].toString());
        LogUtils.e("高德定位city: ==========="+result['city'].toString());
        LogUtils.e("高德定位city: ==========="+result['city'].toString());
        LogUtils.e("高德定位district: ==========="+result['district'].toString());
        LogUtils.e("高德定位adCode: ==========="+result['adCode'].toString());
      });
    });
    _setLocationOption();
  }

设置定位参数_setLocationOption()

///设置定位参数
  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);

      ///开始定位
      _startLocation();
    }
  }

ios配置requestAccuracyAuthorization()

  ///获取iOS native的accuracyAuthorization类型
  void requestAccuracyAuthorization() async {
    AMapAccuracyAuthorization currentAccuracyAuthorization =
    await _locationPlugin.getSystemAccuracyAuthorization();
    if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationFullAccuracy) {
      print("精确定位类型");
    } else if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationReducedAccuracy) {
      print("模糊定位类型");
    } else {
      print("未知定位类型");
    }
  }

开始定位_startLocation()

 ///开始定位
  void _startLocation() {
    if (null != _locationPlugin) {
      _locationPlugin.startLocation();
    }
  }

  ///停止定位
  void _stopLocation() {
    if (null != _locationPlugin) {
      _locationPlugin.stopLocation();
    }
  }

页面销毁时移除处理

 
  void dispose() {
    super.dispose();
    ///移除定位监听
    if (null != _locationListener) {
      _locationListener!.cancel();
    }
    ///销毁定位
    if (null != _locationPlugin) {
      _locationPlugin.destroy();
    }
  }

结果打印:

高德定位==========={callbackTime: 2022-10-10 16:45:06, locationTime: 2022-10-10 16:44:39, locationType: 4, latitude: 34.791413, longitude: 113.80804, accuracy: 73.0, altitude: 0.0, bearing: 0.0, speed: 0.0, country: 中国, province: 河南省, city: 郑州市, district: 金水区, street: 中道东路, streetNumber: 195, cityCode: 0371, adCode: 410105, address: 河南省郑州市金水区中道东路195号靠近正商博雅广场, description: 在正商博雅广场附近}
I/flutter ( 6925): Flutter_Gas_Client | 高德定位latitude===========34.791413
I/flutter ( 6925): Flutter_Gas_Client | 高德定位longitude: ===========113.80804
I/flutter ( 6925): Flutter_Gas_Client | 高德定位country: ===========中国
I/flutter ( 6925): Flutter_Gas_Client | 高德定位province: ===========河南省
I/flutter ( 6925): Flutter_Gas_Client | 高德定位city: ===========郑州市
I/flutter ( 6925): Flutter_Gas_Client | 高德定位city: ===========郑州市
I/flutter ( 6925): Flutter_Gas_Client | 高德定位district: ===========金水区
I/flutter ( 6925): Flutter_Gas_Client | 高德定位adCode: ===========410105

④、在地图上显示自己的位置

  MyLocationStyleOptions _myLocationStyleOptions =
  MyLocationStyleOptions(true);
final AMapWidget map = AMapWidget(
      privacyStatement: ConstConfig.amapPrivacyStatement,
      apiKey: ConstConfig.amapApiKeys,
      //地图样式  默认普通地图 普通视图 normal,卫星视图 satellite, 夜间视图 night, 导航视图 navi, 公交视图 bus,
      mapType: MapType.normal,
      //是否显示3D地图
      buildingsEnabled: true,
      //设置地图默认中心点
      // initialCameraPosition:
      //     CameraPosition(target: LatLng(34.76, 113.78), zoom: 10),
      //是否显示指南针
      compassEnabled: true,
      //比例尺是否显示
      scaleEnabled: true,
      //是否显示路况信息
      trafficEnabled: false,
      //是否显示底图文字
      labelsEnabled: true,
      //旋转手势
      rotateGesturesEnabled: true,
      //滑动手势
      scrollGesturesEnabled: true,
      //倾斜手势
      tiltGesturesEnabled: true,
      //缩放手势
      zoomGesturesEnabled: true,
      //地图创建完成回调,成功后会返回AMapController对象
      onMapCreated: onMapCreated,
      //地图移动回调
      onCameraMove: _onCameraMove,
      // //创建地图时,给marker属性赋值一个空的set,否则后续无法添加marker
      markers: Set<Marker>.of(_markers.values),
      //当前位置显示
      myLocationStyleOptions: _myLocationStyleOptions/*MyLocationStyleOptions(
        true,
        circleFillColor: Colors.lightBlue,
        circleStrokeColor: Colors.blue,
        circleStrokeWidth: 1,
      ),*/
    );

显示效果:

在这里插入图片描述

④.1 定位显示范围:需要放大后一定比例后才显示
MyLocationStyleOptions(
        true,
        circleFillColor: Colors.lightBlue,
        circleStrokeColor: Colors.blue,
        circleStrokeWidth: 1,
      )

显示效果:
在这里插入图片描述

④.2 自定义定位图标
 myLocationStyleOptions: MyLocationStyleOptions(
        true,
        icon:BitmapDescriptor.fromIconPath('image/icon_del.png')
      ),

显示效果:

在这里插入图片描述

三、地图+定位完整界面代码如下:
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:frametrim/map/MapImageUtil.dart';
import 'package:frametrim/utility/log_utils.dart';
import '../../map/const_config.dart';
import 'package:amap_flutter_location/amap_flutter_location.dart';

/*政府端
* 实时监控*/
class GovernmentMonitorPage extends StatefulWidget {
  
  State<StatefulWidget> createState() => GovernmentMonitorState();
}

class GovernmentMonitorState extends State<GovernmentMonitorPage> {
  AMapController? _mapController;

  //需要先设置一个空的map赋值给AMapWidget的markers,否则后续无法添加marker
  final Map<String, Marker> _markers = <String, Marker>{};
  late List<LatLng> makLocations = [
    LatLng(34.80, 113.66), //金水
    LatLng(34.72, 113.64), //二七
    LatLng(34.75, 113.68), //管城
    LatLng(34.75, 113.61), //中原
    LatLng(34.87, 113.62) //惠济
  ];
  late List<String> makerText = ['金水区150', '二七区25', '管城区100', '中原区32', '惠济56'];


  Map<String, Object>? _locationResult;

  StreamSubscription<Map<String, Object>>? _locationListener;

  AMapFlutterLocation _locationPlugin = new AMapFlutterLocation();


  ///自定义定位小蓝点
  MyLocationStyleOptions _myLocationStyleOptions =
  MyLocationStyleOptions(true);

  
  void initState() {
    super.initState();
    initLocation();
  }

  
  Widget build(BuildContext context) {
    ///使用默认属性创建一个地图
    final AMapWidget map = AMapWidget(
      privacyStatement: ConstConfig.amapPrivacyStatement,
      apiKey: ConstConfig.amapApiKeys,
      //地图样式  默认普通地图 普通视图 normal,卫星视图 satellite, 夜间视图 night, 导航视图 navi, 公交视图 bus,
      mapType: MapType.normal,
      //是否显示3D地图
      buildingsEnabled: true,
      //设置地图默认中心点
      // initialCameraPosition:
      //     CameraPosition(target: LatLng(34.76, 113.78), zoom: 10),
      //是否显示指南针
      compassEnabled: true,
      //比例尺是否显示
      scaleEnabled: true,
      //是否显示路况信息
      trafficEnabled: false,
      //是否显示底图文字
      labelsEnabled: true,
      //旋转手势
      rotateGesturesEnabled: true,
      //滑动手势
      scrollGesturesEnabled: true,
      //倾斜手势
      tiltGesturesEnabled: true,
      //缩放手势
      zoomGesturesEnabled: true,
      //地图创建完成回调,成功后会返回AMapController对象
      onMapCreated: onMapCreated,
      //地图移动回调
      onCameraMove: _onCameraMove,
      // //创建地图时,给marker属性赋值一个空的set,否则后续无法添加marker
      markers: Set<Marker>.of(_markers.values),
      myLocationStyleOptions: /*_myLocationStyleOptions*/MyLocationStyleOptions(
        true,
        icon:BitmapDescriptor.fromIconPath('image/icon_del.png')
      ),
    );

    return Scaffold(
      body: AnnotatedRegion(
        value: SystemUiOverlayStyle.dark,
        child: Container(
          height: MediaQuery
              .of(context)
              .size
              .height,
          width: MediaQuery
              .of(context)
              .size
              .width,
          // child: Text('11'),
          child: map,
        ),
      ),
    );
  }

  void onMapCreated(AMapController controller) {
    setState(() {
      _mapController = controller;
      getApprovalNumber();
      _changeCameraPosition();
      _changeZoom();
      for (int i = 0; i < makLocations.length; i++) {
        _addAreaMarker(makLocations[i], i);
      }
    });
  }

  //地图移动回调
  void _onCameraMove(CameraPosition cameraPosition) {
    if (null == cameraPosition) {
      return;
    }
    print('onCameraMove===> ${cameraPosition.toMap()}');
  }

  // 获取审图号
  void getApprovalNumber() async {
    //普通地图审图号
    String? mapContentApprovalNumber =
    await _mapController?.getMapContentApprovalNumber();
    //卫星地图审图号
    String? satelliteImageApprovalNumber =
    await _mapController?.getSatelliteImageApprovalNumber();
  }

  //改变地图中心点
  void _changeCameraPosition() {
    _mapController?.moveCamera(
      CameraUpdate.newCameraPosition(
        CameraPosition(
          //中心点
            target: LatLng(34.80, 113.66),
            //缩放级别
            zoom: 13,
            //俯仰角0°~45°(垂直与地图时为0)
            tilt: 30,
            //偏航角 0~360° (正北方为0)
            bearing: 0),
      ),
      animated: true,
    );
  }

  //缩放地图级别
  void _changeZoom() {
    CameraUpdate.zoomTo(18);
  }

  ///添加一个区域marker
  Future<void> _addAreaMarker(LatLng mLatLng, int index) async {
    final _markerPosition = mLatLng;
    Widget widget = await buildAreaMarkWidget(index);
    Uint8List? bd = await MapImageUtil.convertWidgetToImage(widget);
    final Marker marker = Marker(
        position: _markerPosition,
        //使用默认hue的方式设置Marker的图标
        icon: BitmapDescriptor.fromBytes(bd!),
        // icon:  BitmapDescriptor.fromIconPath('image/distract_bg.png')
        onTap: (id) {
          LogUtil.d('点击Marker$id');
          setState(() {
            _markers.clear();
            for (int i = 0; i < makLocations.length; i++) {
              _addPointMarker(makLocations[i], i);
            }
          });
        });
    //调用setState触发AMapWidget的更新,从而完成marker的添加
    setState(() {
      //将新的marker添加到map里
      _markers[marker.id] = marker;
    });
  }

  ///添加一个点marker-点
  Future<void> _addPointMarker(LatLng mLatLng, int index) async {
    final _markerPosition = mLatLng;
    Widget widget = await buildPointMarkWidget(index);
    Uint8List? bd = await MapImageUtil.convertWidgetToImage(widget);
    final Marker marker = Marker(
        position: _markerPosition,
        //使用默认hue的方式设置Marker的图标
        icon: BitmapDescriptor.fromBytes(bd!),
        // icon:  BitmapDescriptor.fromIconPath('image/distract_bg.png')
        onTap: (id) {
          LogUtil.d('点击Marker$id');
        });
    //调用setState触发AMapWidget的更新,从而完成marker的添加
    setState(() {
      //将新的marker添加到map里
      _markers[marker.id] = marker;
    });
  }

  //Mark样式-区域
  Future<Widget> buildAreaMarkWidget(int index) async {
    //带图片的时候需要先把图片缓存一下,否则不显示
    AssetImage provider = AssetImage('image/distract_bg.png');
    await precacheImage(provider, context);
    // Image image = Image(image: provider);
    return Container(
      alignment: Alignment.center,
      width: 150,
      height: 150,
      decoration: BoxDecoration(
        image: DecorationImage(image: AssetImage('image/distract_bg.png')),
      ),
      child: Directionality(
          textDirection: TextDirection.ltr,
          child: Text(makerText[index],
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 25,
                  fontWeight: FontWeight.bold))),
    );
  }

  //Mark样式-区域
  Future<Widget> buildPointMarkWidget(int index) async {
    //带图片的时候需要先把图片缓存一下,否则不显示
    AssetImage provider = AssetImage('image/cb_select.png');
    await precacheImage(provider, context);
    // Image image = Image(image: provider);
    return Container(
      alignment: Alignment.center,
      width: 150,
      height: 150,
      decoration: BoxDecoration(
        image: DecorationImage(image: AssetImage('image/cb_select.png')),
      ),
      child: Directionality(
          textDirection: TextDirection.ltr,
          child: Text("11",
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 25,
                  fontWeight: FontWeight.bold))),
    );
  }

  /*地图定位*/
  void initLocation() {
    //高德定位
    // AMapFlutterLocation.updatePrivacyShow(true, true);
    // AMapFlutterLocation.updatePrivacyAgree(true);
    // AMapFlutterLocation.setApiKey(
    //     "8c278373b54c9c393c74f1d1a2d31d49", "ios ApiKey");
    ///iOS 获取native精度类型
    if (Platform.isIOS) {
      requestAccuracyAuthorization();
    }
    ///注册定位结果监听
    _locationListener = _locationPlugin
        .onLocationChanged()
        .listen((Map<String, Object> result) {
      setState(() {
        _locationResult = result;
        LogUtils.e("高德定位==========="+result.toString());
        LogUtils.e("高德定位latitude==========="+result['latitude'].toString());
        LogUtils.e("高德定位longitude: ==========="+result['longitude'].toString());
        LogUtils.e("高德定位country: ==========="+result['country'].toString());
        LogUtils.e("高德定位province: ==========="+result['province'].toString());
        LogUtils.e("高德定位city: ==========="+result['city'].toString());
        LogUtils.e("高德定位city: ==========="+result['city'].toString());
        LogUtils.e("高德定位district: ==========="+result['district'].toString());
        LogUtils.e("高德定位adCode: ==========="+result['adCode'].toString());
      });
    });
    _setLocationOption();
  }

  ///设置定位参数
  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);

      ///开始定位
      _startLocation();
    }
  }

  ///获取iOS native的accuracyAuthorization类型
  void requestAccuracyAuthorization() async {
    AMapAccuracyAuthorization currentAccuracyAuthorization =
    await _locationPlugin.getSystemAccuracyAuthorization();
    if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationFullAccuracy) {
      print("精确定位类型");
    } else if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationReducedAccuracy) {
      print("模糊定位类型");
    } else {
      print("未知定位类型");
    }
  }


  ///开始定位
  void _startLocation() {
    if (null != _locationPlugin) {
      _locationPlugin.startLocation();
    }
  }

  ///停止定位
  void _stopLocation() {
    if (null != _locationPlugin) {
      _locationPlugin.stopLocation();
    }
  }
  
  void dispose() {
    super.dispose();

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

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


}

显示效果:
在这里插入图片描述
点击在这里插入图片描述后重绘marker:

在这里插入图片描述

  • 6
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值