Flutter Firebase clustering_google_maps - PullRequest
       8

Flutter Firebase clustering_google_maps

0 голосов
/ 13 апреля 2019

Цель состоит в том, чтобы производить маркеры карты Google, используя кластеры из информации в памяти. В настоящее время я загружаю точки LATLNG из Firebase в локальную память. Затем цель состоит в том, чтобы отобразить эту коллекцию точек на карте в приложении Flutter, используя функцию кластеризации Google Maps. Для этого существует зависимость, называемая clustering_google_maps 0.0.4+2, которая позволяет получить доступ к данным из локальной базы данных (SQLite) или из локальной памяти.

Разработчик рекомендует с большими наборами маркеров в тысячи лучше использовать локальную базу данных (SQLite). В моем случае у меня всего 20-40 маркеров. Может ли кто-нибудь помочь найти решение, объясняющее, как можно использовать данные из локальной памяти для отображения на карте Google?

Быстрый пример из репо

class HomeScreen extends StatefulWidget {
  final List<LatLngAndGeohash> list;

  HomeScreen({Key key, this.list}) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  ClusteringHelper clusteringHelper;
  final CameraPosition initialCameraPosition =
      CameraPosition(target: LatLng(0.000000, 0.000000), zoom: 0.0);

  Set<Marker> markers = Set();

  void _onMapCreated(GoogleMapController mapController) async {
    print("onMapCreated");
    if (widget.list == null) {
      clusteringHelper.database = await AppDatabase.get().getDb();
    }
    clusteringHelper.updateMap();
  }

  updateMarkers(Set<Marker> markers) {
    setState(() {
      this.markers = markers;
    });
  }

  @override
  void initState() {
    if (widget.list != null) {
      initMemoryClustering();
    } else {
      initDatabaseClustering();
    }

    super.initState();
  }

  // For db solution
  initDatabaseClustering() {
    clusteringHelper = ClusteringHelper.forDB(
      dbGeohashColumn: FakePoint.dbGeohash,
      dbLatColumn: FakePoint.dbLat,
      dbLongColumn: FakePoint.dbLong,
      dbTable: FakePoint.tblFakePoints,
      updateMarkers: updateMarkers,
    );
  }

  // For memory solution
  initMemoryClustering() {
    clusteringHelper = ClusteringHelper.forMemory(
      list: widget.list,
      updateMarkers: updateMarkers,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Clustering Example"),
      ),
      body: GoogleMap(
        onMapCreated: _onMapCreated,
        initialCameraPosition: initialCameraPosition,
        markers: markers,
        onCameraMove: (newPosition) => clusteringHelper.onCameraMove(newPosition, forceUpdate: false),
        onCameraIdle: clusteringHelper.onMapIdle,
      ),
      floatingActionButton: FloatingActionButton(
        child:
            widget.list == null ? Icon(Icons.content_cut) : Icon(Icons.update),
        onPressed: () {
          if (widget.list == null) {
            clusteringHelper.whereClause = "WHERE ${FakePoint.dbLat} > 42.6";
            clusteringHelper.updateMap();
          } else {
            clusteringHelper.updateMap();
          }
        },
      ),
    );
  }
}

1 Ответ

0 голосов
/ 17 апреля 2019

Из документов

ТЕХНИКА ПАМЯТИ Для правильной работы у вас должен быть список объекта LatLngAndGeohash. LatLngAndGeohash - простой объект со свойством Location и Geohash, последний генерируется автоматически; вам нужно только местоположение точки.

Для этого решения вы должны использовать конструктор MEMORY ClusteringHelper:

ClusteringHelper.forMemory(...);

Для проверки этой функции вы можете клонировать репозиторий giandifra / clustering_google_maps . Затем измените файл splash.dart, используя следующий код. при вызове HomeScreen из splash.dart

  List<LatLngAndGeohash> markerList = new List<LatLngAndGeohash>();

  @override
  void initState() {
    super.initState();
    markerList.add(LatLngAndGeohash(LatLng(34.0522, -118.2437)));
    markerList.add(LatLngAndGeohash(LatLng(34.0522, -118.2647)));
    markerList.add(LatLngAndGeohash(LatLng(34.0522, -118.2467)));
    markerList.add(LatLngAndGeohash(LatLng(34.0522, -118.2487)));
    markerList.add(LatLngAndGeohash(LatLng(34.0522, -118.2707)));
  }

 @override
   Widget build(BuildContext context) {
     return Scaffold(
        ....
        HomeScreen(list: markerList)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...