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         /// <summary>
28         /// It must be running in main thread.
29         /// </summary>
30         /// <param name="sender"></param>
31         /// <param name="eventData"></param>
32         private void QueryCompletedCallback(object sender, QueryCompletedEventArgs<IList<MapLocation>> eventData)
33         {
34             // Commenting out because I have to disable progress dialog even if the async task was cancelled.
35             //if (eventData.Cancelled)
36             //{
37             //    // Be careful!!! If you throw exception from this point your program will finish with "Unhandled Exception".  
38             //    return;
39             //}
40
41             ReverseGeocodeQuery reverseGeocodeQuery = sender as ReverseGeocodeQuery;
42
43             // Default values
44             var city = AppResources.DefaultCity;
45             var country = AppResources.DefaultCountry;
46
47             Exception errorException = eventData.Error;
48             if (errorException == null)
49             {
50                 if (eventData.Result.Count > 0)
51                 {
52                     if (eventData.Result[0].Information != null
53                         && eventData.Result[0].Information.Address != null)
54                     {
55                         var address = eventData.Result[0].Information.Address;
56                         city = string.IsNullOrEmpty(address.City) ? AppResources.DefaultCity : address.City;
57                         country = string.IsNullOrEmpty(address.Country) ? AppResources.DefaultCountry : address.Country;
58                     }
59                 }
60             }
61
62             if (Page != null)
63             {
64                 Page.OnCompletedReverseGeoCode(reverseGeocodeQuery.GeoCoordinate, city,country);
65             }
66         }
67     }
68 }