Как отобразить маркеры на гугл картах из Firebase в флаттере? - PullRequest
0 голосов
/ 29 марта 2019

Я пытаюсь сделать так, чтобы маркеры появлялись на плагине флаттера карт Google, но я не знаю, что я делаю неправильно.

Я не получаю сообщение об ошибке, ни одной, которую я вижу.

Я использую плагин Google Flutter и облачный Firestore, вот как у меня есть данные в облачном Firestore:

enter image description here

Вот код:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

void main() => runApp(Lugares());

class Lugares extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Lugares',
      home: MapSample(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MapSample extends StatefulWidget {
  @override
  State<MapSample> createState() => MapSampleState();
}

class MapSampleState extends State<MapSample> {
  final Firestore _database = Firestore.instance;
  Completer<GoogleMapController> _controller = Completer();
  Map<MarkerId, Marker> markers = <MarkerId, Marker>{};

  crearmarcadores(){
    _database.collection('Lugares')
              .where('tipo', isEqualTo: 'café')
              .where('tipo', isEqualTo: 'negocio')
              .where('tipo', isEqualTo: 'parque')
              .where('tipo', isEqualTo: 'peluqueria')
              .where('tipo', isEqualTo: 'plaza')
              .where('tipo', isEqualTo: 'restaurant')
              .where('tipo', isEqualTo: 'tienda')
              .getDocuments().then((docs) {
                if(docs.documents.isNotEmpty){
                  for(int i= 0; i < docs.documents.length; i++) {
                    initMarker(docs.documents[i].data, docs.documents[i].documentID);
                  }
                }
              });
  }
  void initMarker(lugar, lugaresid) {
    var markerIdVal = lugaresid;
    final MarkerId markerId = MarkerId(markerIdVal);

    // creating a new MARKER
    final Marker marker = Marker(
      markerId: markerId,
      position: LatLng(lugar['Latitud'], lugar['Longitud']),
      infoWindow: InfoWindow(title: lugar['Lugar'], snippet: lugar['tipo']),
    );

    setState(() {
      // adding a new marker to map
      markers[markerId] = marker;
    });
    }

  static final CameraPosition _kGooglePlex = CameraPosition(
    target: LatLng(37.42796133580664, -122.085749655962),
    zoom: 14.4746,
  );

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: GoogleMap(
        mapType: MapType.hybrid,
        initialCameraPosition: _kGooglePlex,
        onMapCreated: (GoogleMapController controller) {
          _controller.complete(controller);
        },
        myLocationEnabled: true,
         markers: Set<Marker>.of(markers.values),
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _currentLocation,
        label: Text('Ir a mi Ubicacion!'),
        icon: Icon(Icons.location_on),
      ),
    );
  }



void _currentLocation() async {
   final GoogleMapController controller = await _controller.future;
   LocationData currentLocation;
   var location = new Location();
   try {
     currentLocation = await location.getLocation();
     } on Exception {
       currentLocation = null;
       }

    controller.animateCamera(CameraUpdate.newCameraPosition(
      CameraPosition(
        bearing: 0,
        target: LatLng(currentLocation.latitude, currentLocation.longitude),
        zoom: 17.0,
      ),
    ));
  }

}

Надеюсь, кто-нибудь скажет мне, что мне не хватает.

Ответы [ 2 ]

0 голосов
/ 26 мая 2019

Попробуйте удалить предложения where в запросе Firestone. Кажется, вы пытаетесь применить их как логику ИЛИ, но в цепочке, где предложения действуют как AND. Это приведет к пустому списку данных, и ваши маркеры не будут отображаться.

0 голосов
/ 29 марта 2019

вы не вызываете имя функции crearmarcadores(), которая может быть первой проблемой.

может быть, вы можете вызвать метод initState, как показано ниже:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

void main() => runApp(Lugares());

class Lugares extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Lugares',
      home: MapSample(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MapSample extends StatefulWidget {
  @override
  State<MapSample> createState() => MapSampleState();
}

class MapSampleState extends State<MapSample> {
  final Firestore _database = Firestore.instance;
  Completer<GoogleMapController> _controller = Completer();
  Map<MarkerId, Marker> markers = <MarkerId, Marker>{};

  @override
  void initState(){
    crearmarcadores();
    super.initState();
  }

  crearmarcadores(){
    _database.collection('Lugares')
        .where('tipo', isEqualTo: 'café')
        .where('tipo', isEqualTo: 'negocio')
        .where('tipo', isEqualTo: 'parque')
        .where('tipo', isEqualTo: 'peluqueria')
        .where('tipo', isEqualTo: 'plaza')
        .where('tipo', isEqualTo: 'restaurant')
        .where('tipo', isEqualTo: 'tienda')
        .getDocuments().then((docs) {
      if(docs.documents.isNotEmpty){
        for(int i= 0; i < docs.documents.length; i++) {
          initMarker(docs.documents[i].data, docs.documents[i].documentID);
        }
      }
    });
  }
  void initMarker(lugar, lugaresid) {
    var markerIdVal = lugaresid;
    final MarkerId markerId = MarkerId(markerIdVal);

    // creating a new MARKER
    final Marker marker = Marker(
      markerId: markerId,
      position: LatLng(lugar['Latitud'], lugar['Longitud']),
      infoWindow: InfoWindow(title: lugar['Lugar'], snippet: lugar['tipo']),
    );

    setState(() {
      // adding a new marker to map
      markers[markerId] = marker;
    });
  }


  static final CameraPosition _kGooglePlex = CameraPosition(
    target: LatLng(37.42796133580664, -122.085749655962),
    zoom: 14.4746,
  );

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: GoogleMap(
        mapType: MapType.hybrid,
        initialCameraPosition: _kGooglePlex,
        onMapCreated: (GoogleMapController controller) {
          _controller.complete(controller);
        },
        myLocationEnabled: true,
        markers: Set<Marker>.of(markers.values),
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _currentLocation,
        label: Text('Ir a mi Ubicacion!'),
        icon: Icon(Icons.location_on),
      ),
    );
  }



  void _currentLocation() async {
    final GoogleMapController controller = await _controller.future;
    LocationData currentLocation;
    var location = new Location();
    try {
      currentLocation = await location.getLocation();
    } on Exception {
      currentLocation = null;
    }

    controller.animateCamera(CameraUpdate.newCameraPosition(
      CameraPosition(
        bearing: 0,
        target: LatLng(currentLocation.latitude, currentLocation.longitude),
        zoom: 17.0,
      ),
    ));
  }

}
...