为什么我无法在 Google Map Flutter 上看到存储在 RTDB Firebase 上的其他用户的标记

问题描述 投票:0回答:1

问题是我只能在 Google 地图上看到自己的标记,而看不到其他用户的标记,即使其他用户数据(即纬度和经度)存储在实时数据库中。

下面你可以看到代码:

final DatabaseReference _locationRef =
      FirebaseDatabase.instance.ref('user_locations/$uid');

// For fetching icon from Firebase Storage
getIcons() async {
    Reference referenceRoot =
        FirebaseStorage.instance.ref().child('img/profile_pictures/$uid');
    var imageUrl = await referenceRoot.getDownloadURL();
    try {
      final Uint8List markerImageBytes = await DefaultCacheManager()
          .getSingleFile(imageUrl)
          .then((file) => file.readAsBytes());
      final ui.Codec codec = await ui.instantiateImageCodec(markerImageBytes,
          targetWidth: 100, targetHeight: 100);
      final ByteData? byteData = await codec.getNextFrame().then((frameInfo) =>
          frameInfo.image.toByteData(format: ui.ImageByteFormat.png));
      return BitmapDescriptor.fromBytes(byteData!.buffer.asUint8List());
    } catch (e) {
      print('Error on getting icon: $e');
    }
  }

// Saving user location
void saveUserLocation() async {
    try {
      await _locationRef.set({
        "latitude": _currentPosition!.latitude.toString(),
        "longitude": _currentPosition!.longitude.toString()
      });
      print("Database Written in real-time");
    } catch (e) {
      print("Error writting user location: $e"); //
    }
  }
 void updateUserLocation() async {
    try {
      await _locationRef.update({
        "latitude": _currentPosition!.latitude.toString(),
        "longitude": _currentPosition!.longitude.toString()
      });
      print("Database Updated in real-time");
    } catch (e) {
      print("Error updating user location: $e"); //
    }
  }

  void getLocation() async {
    Geolocator.getPositionStream(
      locationSettings: const LocationSettings(
        accuracy: LocationAccuracy.bestForNavigation,
      ),
    ).listen((position) {
      setState(() {
        _currentPosition = LatLng(position.latitude, position.longitude);
        saveUserLocation();
        _createMarker();
      });
    });
  }

  // Function for creating marker
  Future<Set<Marker>> _createMarker() async {
    final icon = await getIcons();
    if (_currentPosition != null && icon != null) {
      Marker userMarker;
      _locationRef.onValue.listen((event) {
        Map<dynamic, dynamic> userLocation =
            event.snapshot.value as Map<dynamic, dynamic>;
        userLocation.forEach((key, value) {
          double? latitude = double.tryParse(userLocation['latitude'] ?? '');
          double? longitude = double.tryParse(userLocation['longitude'] ?? '');
          if (latitude != null && longitude != null) {
            userMarker = Marker(
              markerId: MarkerId(uid!),
              position: LatLng(latitude, longitude),
              icon: icon,
              infoWindow: InfoWindow(
                title: "$username",
                snippet: "$username's Location",
              ),
            );
            setState(() {
              marker.clear();
              marker.add(userMarker);
            });
          } else {
            print('Invalid latlng for user with key: $key');
          }
        });
      });
    }

    return marker;
  }

  void _initMapAndMarkers() async {
    final markers = await _createMarker();
    setState(() {
      _markers = markers; // Assuming _markers is a Set<Marker> in your state
    });
  }

  GoogleMap(
              mapType: MapType.normal,
              zoomControlsEnabled: true,
              initialCameraPosition: CameraPosition(
                target: _currentPosition ?? const LatLng(0, 0),
              ),
              onMapCreated: (GoogleMapController controller) {
                if (!_googleMapController.isCompleted) {
                  _googleMapController.complete(controller);
                }
              },
              markers: Set<Marker>.of(_markers),
            ),

我试图获取所有其他用户标记(即每个用户都可以通过地图看到彼此的位置)。

flutter google-maps firebase-realtime-database firebase-storage
1个回答
0
投票

您的

_locationRef
指向特定用户的数据,这似乎是您从数据库读取的唯一路径。

如果您想从所有 UID 值读取数据,请从更高一级读取并循环结果,如监听值列表的文档中所示。

© www.soinside.com 2019 - 2024. All rights reserved.