WeatherInformation WP8: MapPage improvements
[CSharpForFun/.git] / WindowsPhone / WP8 / WeatherInformation / WeatherInformation / Model / ReverseGeoCode.cs
1 using Microsoft.Phone.Maps.Services;
2 using System;
3 using System.Collections.Generic;
4 using System.Device.Location;
5 using WeatherInformation.Resources;
6
7 namespace WeatherInformation.Model
8 {
9     class ReverseGeoCode
10     {
11         public interface IReverseGeoCode
12         {
13             void OnCompletedReverseGeoCode(GeoCoordinate geoCoordinate, string city, string country);
14         }
15
16         public IReverseGeoCode Page { get; set; }
17         public GeoCoordinate CoorDinate { get; set; }
18
19         public void DoReverseGeocode(GeoCoordinate geoCoordinate)
20         {
21             var currentReverseGeocodeQuery = new ReverseGeocodeQuery();
22             currentReverseGeocodeQuery.GeoCoordinate = geoCoordinate;
23             currentReverseGeocodeQuery.QueryCompleted += QueryCompletedCallback;
24             currentReverseGeocodeQuery.QueryAsync();
25         }
26
27         private void QueryCompletedCallback(object sender, QueryCompletedEventArgs<IList<MapLocation>> eventData)
28         {
29             // Commenting out because I have to disable progress dialog even if the async task was cancelled.
30             //if (eventData.Cancelled)
31             //{
32             //    // Be careful!!! If you throw exception from this point your program will finish with "Unhandled Exception".  
33             //    return;
34             //}
35
36             ReverseGeocodeQuery reverseGeocodeQuery = sender as ReverseGeocodeQuery;
37
38             // Default values
39             var city = AppResources.DefaultCity;
40             var country = AppResources.DefaultCountry;
41
42             Exception errorException = eventData.Error;
43             if (errorException == null)
44             {
45                 if (eventData.Result.Count > 0)
46                 {
47                     if (eventData.Result[0].Information != null
48                         && eventData.Result[0].Information.Address != null)
49                     {
50                         var address = eventData.Result[0].Information.Address;
51                         city = string.IsNullOrEmpty(address.City) ? AppResources.DefaultCity : address.City;
52                         country = string.IsNullOrEmpty(address.Country) ? AppResources.DefaultCountry : address.Country;
53                     }
54                 }
55             }
56
57             if (Page != null)
58             {
59                 Page.OnCompletedReverseGeoCode(reverseGeocodeQuery.GeoCoordinate, city,country);
60             }
61         }
62     }
63 }