I am trying to populate a map with locations obtained from an API but it is proving very problematic. When I create a pin from the code behind it shows fine, but it does not show when I use xaml. I would really like to understand what I am doing wrong, thanks! The API successfully stores a longitude and latitude in the ObservableCollection
and I can confirm that through debugging, it is just not represented on the map!
View
<Grid> <maps:Map x:Name="ItemsSource="{Binding Locations}"> <maps:Map.ItemTemplate> <DataTemplate> <maps:Pin Position="{Binding Address="{Binding Name}" Label="{Binding Description}" /> </DataTemplate> </maps:Map.ItemTemplate> </maps:Map> </Grid>
Code-behind
private ITestApiService _testAPIService = new TestApiService(); public MainPage() { InitializeComponent(); BindingContext = new MainPageViewModel(_testAPIService); map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(51.507351, -0.127758), Distance.FromMiles(100))); } }
ViewModel
class MainPageViewModel { public ObservableCollection<Location> Locations { get; set; } private ITestApiService TestApiService{ get; set; } public MainPageViewModel(ITestApiService testApiService) { TestApiService= testApiService; PopulateEventMapView(); } private async void PopulateEventMapView() { var events = await TestApiService.GetEvents(); Locations = CreateLocation(events); } private ObservableCollection<Location> CreateLocation(List<Event> events) { var locations = new ObservableCollection<Location>(); foreach (var eventItem in events) { locations.Add(new Location(eventItem.Name, eventItem.Description, new Position(eventItem.Venue.Latitude, eventItem.Venue.Longitude))); } return locations; } }