授予权限后,重新加载我的位置按钮

时间:2019-12-07 21:26:01

标签: google-maps flutter

背景

我正在使用google_maps_flutter包来显示带有与房屋相对应的标记的地图。为避免设备超载,我只在用户所看位置附近装载房屋。为了简化操作,我要求用户提供位置信息并将其提供给Google地图,以便显示“我的位置”按钮。

问题

如果已经授予位置访问权限,则它会按预期工作。不管谁已经加载了地图,“我的位置”按钮都不会显示。

当前,如果在屏幕上显示地图时授予了位置许可,我只需将相机移到其位置即可。这是一个不错的解决方法,但我宁愿让用户决定要看的地方。

在已加载地图的情况下授予权限时,如何加载按钮?

尝试

  1. 我只是尝试设置状态。
  2. 手动将地图标记为肮脏。
  3. 使用测试方法强制地图重新加载选项。

我已经检查了我可以使用的所有可用方法,因此目前我怀疑是否还有其他选择。如果是这种情况,我将其报告为错误。

我的代码

  @override
  Widget build(BuildContext context) {
    // Load markers when permission is granted.
    location.hasPermission().then((currPerm) async {
      if (!currPerm) {
        bool newPerm = await location.requestPermission();
        if (newPerm) {
          LocationData data = await location.getLocation();
          (await mapController.future).moveCamera(CameraUpdate.newLatLng(LatLng(data.latitude, data.longitude)));
        }
      }
    });

    GoogleMap map = GoogleMap(
      initialCameraPosition: CameraPosition(
        target: INIT_POS,
        zoom: 11.5,
      ),
      myLocationEnabled: true,
      myLocationButtonEnabled: true,
      trafficEnabled: true,
      markers: markers,
      onMapCreated: (newController) => mapController.complete(newController),
      onCameraIdle: () async {
        // Load markers when the camera stops moving.
        LatLngBounds bounds = await (await mapController.future).getVisibleRegion();
        loadMarkers(
          LatLng(
            (bounds.northeast.latitude + bounds.southwest.latitude)/2,
            (bounds.northeast.longitude + bounds.southwest.longitude)/2
          ),
        );
      },
    );
    return map;
  }

1 个答案:

答案 0 :(得分:1)

google_maps_flutter: ^0.5.23+1开始,我通过为myLocationEnabled分配变量并在获得位置许可后更改其值来解决该问题。如果您对true进行硬编码,它将无法正常工作。

GoogleMap map = GoogleMap(
      myLocationEnabled: _isLocationGranted,
      ...

因此,_isLocationGranted最初是false。获得位置许可后,将其设置为true并重建窗口小部件(通过调用setState(),触发BlocBuilder()或您使用的任何方法)。

另一个相关参数myLocationButtonEnabled: true似乎不需要此处理。