使用Flutter Google Maps插件保持所有标记物可见

3
我正在使用Flutter创建一个应用程序,使用这个软件包:https://github.com/flutter/plugins/tree/master/packages/google_maps_flutter
我从我的服务器获取位置列表,在地图上必须放置标记。 我面临的问题是,所有放置在地图上的标记都必须可见。 位置列表是随机的,因此我不能假设它们都在一个城市中,还是分布在整个地球上。 我该如何保持所有标记可见?

1
CameraPosition 的缩放设置为1。 - Akora Ing. DKB
1个回答

5

请尝试下面的代码。它可以与数百个标记一起使用。

  // Set<Marker> _markers = Set();
  @override
  Widget build(BuildContext context) {
    return GoogleMap(
      mapType: MapType.hybrid,
      myLocationEnabled: true,
      initialCameraPosition: CameraPosition(
          target: LatLng(_bloc.location.latitude, _bloc.location.longitude),
          zoom: 3),
      markers: _markers,
      onMapCreated: (GoogleMapController controller) {
        _controller.complete(controller);
        Future.delayed(
            Duration(milliseconds: 200),
            () => controller.animateCamera(CameraUpdate.newLatLngBounds(
                MapUtils.boundsFromLatLngList(
                    _markers.map((loc) => loc.position).toList()),
                1)));
      },
    );
  }

map_utils.dart

import 'package:google_maps_flutter/google_maps_flutter.dart';

class MapUtils {
  static LatLngBounds boundsFromLatLngList(List<LatLng> list) {
    double x0, x1, y0, y1;
    for (LatLng latLng in list) {
      if (x0 == null) {
        x0 = x1 = latLng.latitude;
        y0 = y1 = latLng.longitude;
      } else {
        if (latLng.latitude > x1) x1 = latLng.latitude;
        if (latLng.latitude < x0) x0 = latLng.latitude;
        if (latLng.longitude > y1) y1 = latLng.longitude;
        if (latLng.longitude < y0) y0 = latLng.longitude;
      }
    }
    return LatLngBounds(northeast: LatLng(x1, y1), southwest: LatLng(x0, y0));
  }
} 

6
MapUtils 是来自哪里的? - Alex
@Alex请检查编辑并移除踩票。 - Shadab Hashmi
我不能删除它,因为我没有放置它。我通常只放置积极的内容 :) - Alex
1
它运行得非常好。关于此的null-safety版本在这里附上,https://github.com/MuthuHere/GoogleMapFlutterSetBounds/blob/main/README.md - IamVariable

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接