I am trying to add pushpins to a Bing Map. The push pins are got from a JSON feed. I would like to get something like this: My code does not work for the first time alone and I cant understand why. My map ViewModel is
public class MapViewModel : INotifyPropertyChanged
{
public static ObservableCollection<PushpinModel> pushpins = new ObservableCollection<PushpinModel>();
public static ObservableCollection<PushpinModel> Pushpins
{
get { return pushpins; }
set { pushpins = value; }
}
}
The Map xaml cs is:
//Map.xaml.cs
public partial class Map : PhoneApplicationPage
{
#define DEBUG_AGENT
private IGeoPositionWatcher<GeoCoordinate> watcher;
private MapViewModel mapViewModel;
public Map()
{
InitializeComponent();
mapViewModel = new MapViewModel();
this.DataContext = mapViewModel;
}
private void page_Loaded(object sender, RoutedEventArgs e)
{
if (watcher == null)
{
#if DEBUG_AGENT
watcher = new Shoporific.My.FakeGPS();
#else
watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
#endif
}
watcher.Start();
mapViewModel.Center = watcher.Position.Location;
PushpinModel myLocation = new PushpinModel() { Location = mapViewModel.Center, Content = "My Location" };
MapViewModel.Pushpins.Add(myLocation);
myLocation.RefreshNearbyDeals();
watcher.Stop();
}
}
Finally, the PushPinModelClass:
public class PushPinModel
{
public void RefreshNearbyDeals()
{
System.Net.WebClient wc = new WebClient();
wc.OpenReadCompleted += wc_OpenReadCompleted;
wc.OpenReadAsync(" a valid uri");
}
void wc_OpenReadCompleted(object sender, System.Net.OpenReadCompletedEventArgs e)
{
var jsonStream = e.Result;
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Deal[]));
Deal[] deals = (ser.ReadObject(jsonStream) as Deal[]);
if (deals.Any())
{
var currentLocation = MapViewModel.Pushpins.Where(pin => pin.Content == "My Location");
MapViewModel.Pushpins = new ObservableCollection<PushpinModel>();
foreach (var deal in deals)
MapViewModel.Pushpins.Add(new PushpinModel()
{
Content = deal.Store,
Location = new GeoCoordinate(deal.Location.Latitude, deal.Location.Longtitude),
Offers = deal.Offers,
});
}
}
}
I am a bit confused that the Pushpins except "My Location" dont show up only on the first time. They appear as expected the second time onwards(If I navigate back and then move to the Map screen again).