Flutter-- 高德地图定位

794 阅读1分钟

AMapWidget使用

采取思路

  • 通过bool值判断,是否移动地图中心点。
  • 将定位信息保存到本地,下次初始化中心点使用
AMapController? _controller;
bool isChangeLocation = false;

AMapWidget(
  ///初始化中心定
  initialCameraPosition: CameraPosition(
    target: LatLng(SpUtil.getDouble(SpKey.LatitudeKey) ?? 39.909187, Sp.getDouble(SpKey.LongitudeKey) ?? 116.397451,),
    zoom: 16,
  ),
  /// 我的位置自定义配置
  myLocationStyleOptions: MyLocationStyleOptions(
    true,
    circleFillColor: Colors.lightBlue,
    circleStrokeColor: Colors.blue,
    circleStrokeWidth: 1,
  ),
  /// 地图创建成功回调
  onMapCreated: (AMapController controller) async {
    _controller = controller;
  },
  /// 定位回调
  onLocationChanged: (AMapLocation location) {
    if (!isChangeLocation) {
      _moveCamera(location.latLng);
      isChangeLocation = true;
      Sp.setDouble(SpKey.LatitudeKey, location.latLng.latitude);
      Sp.setDouble(SpKey.LongitudeKey, location.latLng.longitude);
    }
  },
  /// POI点击回调
  onPoiTouched: (AMapPoi poi) {
    print(poi.name);
  },
);
//移动地图中心点
void _moveCamera(LatLng currentLatLng) {
  if (null != _controller) {
    _controller!.moveCamera(CameraUpdate.newCameraPosition(CameraPosition(
      target: currentLatLng,
      zoom: 16,)));
  }
}

高德地图定位

  • initState()方法中初始化定位Option以及创建监听定位变化Stream
  • 开启定位
  • dispose()中_locationListener!.cancel();_locationPlugin.destroy();

AMapFlutterLocation _locationPlugin = new AMapFlutterLocation();
StreamSubscription<Map<String, Object>>? _locationListener;

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

  AMapLocationOption loacationOption = AMapLocationOption(
    onceLocation: true,
  );
  _locationPlugin.setLocationOption(loacationOption);
  _locationListener = _locationPlugin.onLocationChanged().listen((Map<String, Object> result) {
  /// 处理模型转换,或者与GetController绑定,更新widget
  
  });
  _locationPlugin.startLocation();
}

QA

  • 想问下,Flutter高德地图搜索的插件,官方有出来吗?