首页 > 解决方案 > 在 google_maps_flutter 中获取可见标记

问题描述

使用Google Maps for Flutter我在地图上的不同位置放置了一些标记。我的 Flutter 应用程序上有一个单独的 RaisedButton,只有当其中一个或多个标记当前在地图上可见时,我才需要它可见。

如何做到这一点?我为 Google Maps API 找到了一个有点类似的解决方案,但我需要在 Flutter 上使用 google_maps_flutter。

标签: google-mapsflutterflutter-dependencies

解决方案


LatLngBounds具有特定的方法,称为contains()which 与GoogleMapController's一起工作getVisibleRegion()

来自官方文档:

contains(LatLng point) → bool
Returns whether this rectangle contains the given LatLng.

用法:

Completer<GoogleMapController> _controller = Completer();

static final CameraPosition _positionCenter = CameraPosition(
    target: LatLng(40.730610, -73.935242),
    zoom: 3.5,
);

Future<LatLngBounds> _getVisibleRegion() async {
    final GoogleMapController controller = await _controller.future;
    final LatLngBounds bounds = await controller.getVisibleRegion();
    return bounds;
}

@override
Widget build(BuildContext context) {
    void checkMarkers() async {
        LatLngBounds bounds = await _getVisibleRegion();
        Set<Marker> markers = Set<Marker>.of(markers.values);

        markers.forEach((marker) {
            print('Position: ${ marker.position } - Contains: ${ bounds.contains(marker.position) }');
        });
    }

    return GoogleMap(
        mapType: MapType.normal,
        markers: Set<Marker>.of(markers.values),
        initialCameraPosition: _positionCenter,
        onCameraIdle: () {
            checkMarkers();
        },
        onMapCreated: (GoogleMapController controller) async {
            _controller.complete(controller);
            checkMarkers();
        },
    );
}

推荐阅读