Home > OS >  flutter live location tracking
flutter live location tracking

Time:06-20

User1(the one being tracked) will broadcast the current location by saving the data to the firestore database.

Future<void> _listenLocation() async {

    _locationSubscription = location.onLocationChanged.handleError((onError) {
      print(onError);
      _locationSubscription?.cancel();
      setState(() {
        _locationSubscription = null;
      });
    }).listen((loc.LocationData currentlocation) async {
      await FirebaseFirestore.instance.collection('location').doc('user1').set({
        'latitude': currentlocation.latitude,
        'longitude': currentlocation.longitude,
        'name': 'john'
      }, SetOptions(merge: true));
    });
  }

And then, the user shall be able to retrieve the location data from the database and return the google map with marker to track the person.

body: StreamBuilder(
      stream: FirebaseFirestore.instance.collection('location').snapshots(),
      builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (_added) {
          mymap(snapshot);
        }
        if (!snapshot.hasData) {
          return Center(child: CircularProgressIndicator());
        }
         return GoogleMap(
              mapType: MapType.normal,
              markers: {
                Marker(
                    position: LatLng(
                      snapshot.data!.docs.singleWhere(
                              (element) => element.id == widget.user_id)['latitude'],
                      snapshot.data!.docs.singleWhere(
                              (element) => element.id == widget.user_id)['longitude'],
                    ),
                    markerId: MarkerId('id'),
                    icon: BitmapDescriptor.defaultMarkerWithHue(
                        BitmapDescriptor.hueMagenta)),
              },

I am actually following the youtube video and the using the related code from the following link

I want both the users (the one being tracked and the listener) to use the same app. I have already implemented it in my app but, I do not understand how the listener would be able to listen to a particular user when there are so many other users in the database as well. In this video, there is only 1 user data being saved which is easily retrieved, however, in my case do I need to have the specific document id of the collection of the user being tracked to be able to fetch the data? And that too shall be unique?

CodePudding user response:

If you want to listen to a specific document, you'll indeed need to know the ID of that document. The two most common ways of getting such a document ID are:

  • Show a list of all relevant documents to the listening user, let them pick one, and them continue with just that document ID.

  • Have the sending user share their document ID with the listening user, for example through Firebase Dynamic Links.

  • Related