I have two methods:
private async Task<GeoCoordinate> CenterMapOnMyLocation()
{
Geolocator myGeolocator = new Geolocator();
Geoposition myGeoposition = await myGeolocator.GetGeopositionAsync();
Geocoordinate myGeocoordinate = myGeoposition.Coordinate;
GeoCoordinate myGeoCoordinate =
ConvertGeocoordinate(myGeocoordinate);
MapCenter = myGeoCoordinate;
if (MyLocation.Latitude == 0 && MyLocation.Longitude == 0)
{
MyLocation = MapCenter;
}
return myGeoCoordinate;
}
and
private void GetClosestLocations(GeoCoordinate myLocation)
{
var locations = new ObservableCollection<PushPinModel>
{
new PushPinModel
{
Location = new GeoCoordinate(51.569593, 10.103504),
LocationName = "1"
},
new PushPinModel
{
Location = new GeoCoordinate(-45.569593, 1.103504),
LocationName = "2"
},
new PushPinModel
{
Location = new GeoCoordinate(0, 0),
LocationName = "3"
}
};
foreach (var location in locations)
{
location.DistanceToMyLocation = HaversineDistance(myLocation, location.Location);
}
Treks = new ObservableCollection<PushPinModel>(locations.OrderBy(l => l.DistanceToMyLocation).Take(2).ToList());
}
and in the constructor I have something like this:
public NearbyControlViewModel()
{
var test = CenterMapOnMyLocation();
GetClosestLocations(test);
}
Now, my problem is that when the second method is called in the constructor, the "test" variable is not initialized yet... because it's async. What I want to do is wait for it to get initialized and after that call the second method. If I call my second method from the async method I get an exceptions: InvalidOperationException - Collection is in non writeable mode. "Treks" value is binded to a MapItemsControl. So i guess the problem something about threads.