Home > OS >  Cant insert pins on map from Firebase database - XAML
Cant insert pins on map from Firebase database - XAML

Time:04-12

I am using this article to populate my map with pins.

I have the following code to display pins from my firebase database in a Xamarin.Forms.Maps

PageMap.xaml.cs:

            public PageMap()
            {
                InitializeComponent();
    
                BindingContext = this;
    
                databaseLoad();
    
            }
    
            public ObservableCollection<MyDatabaseRecord> DatabaseItems { get; set; } = new
      ObservableCollection<MyDatabaseRecord>();
    
            FirebaseClient firebaseClient = new FirebaseClient("firebaselink");
    
    
            private void databaseLoad()
            {
                var collection = firebaseClient
                    .Child("Localizacoes")
                    .AsObservable<MyDatabaseRecord>()
                    .Subscribe((dbevent) =>
                    {
                        if (dbevent != null)
                        {
                            DatabaseItems.Add(dbevent.Object);
                        }
                    });
            }

PageMap.xaml:

<Grid>
        <maps:Map x:Name="map"
                  ItemsSource="{Binding DatabaseItems}">
            <maps:Map.ItemTemplate>
                <DataTemplate>
                    <maps:Pin Position="{Binding Position}"
                              Address="{Binding Address}"
                              Label="{Binding Description}" />
                </DataTemplate>
            </maps:Map.ItemTemplate>
        </maps:Map>
</Grid>

(EDIT) MyDatabaseRecord.Cs:

public class MyDatabaseRecord
{
    public string Address { get; set; }
    public string Description { get; set; }
    public double Lat { get; set; }
    public double Long { get; set; }

}

And my database looks like this

My problem here is that, the pin is generated with the right address and description, but the position returns as 0,0 instead of the one present on the database.

What changes can I make for it to work? Thanks in advance

CodePudding user response:

you could do something like this to dynamically create the position object from your string

public class MyDatabaseRecord
{
    public string Address { get; set; }
    public string Description { get; set; }
    public string Position { get; set; }
    
    private Position parsedPosition;

    public Position ParsedPosition { 
      get {
         if (parsedPosition != null) return parsedPosition;

         var pos = Position.Split(',');
         double lat = double.Parse(pos[0]);
         double lng = double.Parse(pos[1]);
         parsedPosition = new Position(lat,lng);
         return parsedPosition;
      }
    }
}
  • Related