如何从 firebase 数据库中获取特定值?

How to get specific value from firebase database?

我想从 Firebase 数据库中获取地理定位数据,即纬度和经度以进行距离计算。

这是我用来计算距离的方法。

    namespace CoronaGo
    {
        public partial class MainPage : ContentPage
        {
            FirebaseHelper firebaseHelper = new FirebaseHelper();
            public MainPage()
            {
                InitializeComponent();
            }
            protected async override void OnAppearing()
            {
                base.OnAppearing();
                await firebaseHelper.GetAllGetLocation();
            }
            private async void Location_Clicked(object sender, EventArgs e)
            {
                var GetLocation = await firebaseHelper.GetAllGetLocation();
                try
                {
                    var location = await Geolocation.GetLastKnownLocationAsync();
                    if (location == null)
                    {
                        if (location.IsFromMockProvider)
                        {
                            location = await Geolocation.GetLocationAsync(new GeolocationRequest()
                            {
                                DesiredAccuracy = GeolocationAccuracy.High,
                                Timeout = TimeSpan.FromSeconds(30)
                            });
                        }
                        
                    }
                    if (location == null)
                    {
                        LabelLocation.Text = "No GPS Found";
                        UserDialogs.Instance.Toast("Can't Locate Location");
                    }
                    else
                    {
                        LabelLocation.Text = $"{location.Latitude} , {location.Longitude}";
                        Location current = new Location(location.Latitude, location.Longitude);
                        Location redzone = new Location(?????, ?????);
                        double distance = Location.CalculateDistance(current, redzone, DistanceUnits.Kilometers);
                        Distance.Text = distance.ToString("0.000")+" km";
                        if (distance < 1)
                        {
                            UserDialogs.Instance.Toast("You are less than 1km from RED ZONE");
                            await Navigation.PushAsync(new Alert());
                        }
                        else
                            UserDialogs.Instance.Toast("You are in SAFE ZONE");
                    }       
                }
    }

我应该在“??????, ??????”中写什么?以便在 Firebase 数据库中获取纬度和经度。

下面是我的Firebase.cs

namespace CoronaGo
{
    public class FirebaseHelper
    {
        FirebaseClient firebase = new FirebaseClient("https://myfirebase.firebaseio.com/");
        public async Task AddLocation(double la, double lo, string loc)
        {
            await firebase
                .Child("RedZoneLocation")
                .PostAsync(new GetLocation()
                { 
                    Latitude = la, 
                    Longtitude = lo, 
                    Location = loc
                });
        }

        public async Task<List<GetLocation>> GetAllGetLocation()
        {
            return (await firebase.Child("RedZoneLocation").OnceAsync<GetLocation>()).Select(item => new GetLocation
            {
                Latitude = item.Object.Latitude,
                Longtitude = item.Object.Longtitude,
                Location = item.Object.Location
            }).ToList();
        }
    }

}

下面是我的GetLocation.cs

namespace CoronaGo
{
    public class GetLocation
    {
        public double Latitude { get; set; }
        public double Longtitude { get; set; }
        public string Location { get; set; }
    }
}

请帮帮我,谢谢。我是 xamarin 的新手

假设 lat, log 存储为

Users
   user_id
      lat
      lng
      other details

FirebaseDatabase.getInstance().getReference().child("users")
        .child(user_id)
        .addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (snapshot.exists()) {
                    double lat = Double.parseDouble(snapshot.child("lat").toString());
                    double lon = Double.parseDouble(snapshot.child("lon").toString());
                    Location DBlocation = new Location(lat, lon);
                    double kilometers = Location.CalculateDistance(current, DBlocation, DistanceUnits.Kilometers);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });

我已经解决了问题。 下面是我的完整源代码。 非常感谢你帮助我。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Essentials;
using System.Diagnostics;
using Acr.UserDialogs;
using System.Threading;

namespace CoronaGo
{
    
    public partial class MainPage : ContentPage
    {
        FirebaseHelper firebaseHelper = new FirebaseHelper();
        public MainPage()
        {
            InitializeComponent();
        }
        /*protected async override void OnAppearing()
        {
            base.OnAppearing();
            var loc = await firebaseHelper.GetAllGetLocation();
        }*/
        private async void Location_Clicked(object sender, EventArgs e)
        {
            var trigger = 0;
            List<GetLocation> GetLocation = await firebaseHelper.GetAllGetLocation();
            try
            {
                CancellationTokenSource cts;
                var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10));
                cts = new CancellationTokenSource();
                var location = await Geolocation.GetLocationAsync(request, cts.Token);
                var loc = await firebaseHelper.GetAllGetLocation();

                if (location == null)
                {
                    if (location.IsFromMockProvider)
                    {
                        location = await Geolocation.GetLocationAsync(new GeolocationRequest()
                        {
                            DesiredAccuracy = GeolocationAccuracy.Medium,
                            Timeout = TimeSpan.FromSeconds(10)
                        });
                    }
                }
                if (location == null)
                {
                    LabelLocation.Text = "No GPS Found";
                    UserDialogs.Instance.Toast("Can't Locate Location");
                }
                else
                {
                    LabelLocation.Text = $"{location.Latitude} , {location.Longitude}";
                    Location current = new Location(location.Latitude, location.Longitude);
                    foreach (GetLocation item in GetLocation)
                    {
                       Location redzone = new Location(item.Latitude, item.Longtitude);
                       double distance = Location.CalculateDistance(current, redzone, DistanceUnits.Kilometers);
                        if (distance < 1)
                        {
                            Distance.Text = distance.ToString("0.00") + " km";
                            UserDialogs.Instance.Toast("You are less than 1km from RED ZONE");
                            await Navigation.PushAsync(new Alert());
                            trigger = 1;
                        }
                        if (trigger != 1)
                        {
                            UserDialogs.Instance.Toast("You are at SAFE ZONE");
                        }

                    }
                }       
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                Debug.WriteLine($"Location not supported on device: {fnsEx.Message}");
            }
            catch (FeatureNotEnabledException fneEx)
            {
                Debug.WriteLine($"Location not enabled on device: {fneEx.Message}");
            }
            catch (PermissionException pEx)
            {
                Debug.WriteLine($"Permission failed: {pEx.Message}");
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Alert", ex.Message, "Ok");
            }
        }

    }
}