Advertisement
Guest User

Ruairi

a guest
Apr 18th, 2014
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.07 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using System.Windows.Navigation;
  8. using Microsoft.Phone.Controls;
  9. using Microsoft.Phone.Shell;
  10. using Microsoft.Phone.Maps.Controls;
  11. using System.Device.Location;
  12. using Windows.Devices.Geolocation;
  13. using System.Windows.Threading;
  14. using System.Windows.Media;
  15. using System.Windows.Shapes;
  16. using System.Threading.Tasks;
  17. using System.IO.IsolatedStorage;
  18. using Microsoft.Phone.Maps.Services;
  19. using System.Text;
  20. using MyTouristApp.Resources;
  21. using MyTouristApp.Utility;
  22. using MyTouristApp.Data;
  23. using System.IO;
  24. using System.Runtime.Serialization.Json;
  25. using System.Globalization;
  26. using Microsoft.Phone.Maps.Toolkit;
  27. using System.Collections.ObjectModel;
  28.  
  29.  
  30.  
  31.  
  32. namespace MyTouristApp
  33. {
  34. public partial class Page2 : PhoneApplicationPage
  35. {
  36. GeoCoordinateWatcher myWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
  37. MapPolyline line;
  38. DispatcherTimer _timer = new DispatcherTimer();
  39. long _startTime;
  40.  
  41. GeoCoordinateWatcher watcher;
  42. PlacesList placesListObj;
  43.  
  44. private string currentLatitude = string.Empty;
  45. private string currentLongitude = string.Empty;
  46. private string prevLatitude = string.Empty;
  47. private string prevLongitude = string.Empty;
  48.  
  49. private Boolean isPosSet = false;
  50.  
  51. // Constructor
  52. public Page2()
  53. {
  54. InitializeComponent();
  55. if (getConsentStatus())
  56. fetchUserLocation();
  57.  
  58. _timer.Interval = TimeSpan.FromSeconds(1);
  59. _timer.Tick += Timer_Tick;
  60.  
  61. // create a line which illustrates the users path
  62. line = new MapPolyline();
  63. line.StrokeColor = Colors.Red;
  64. line.StrokeThickness = 5;
  65. myMap.MapElements.Add(line);
  66.  
  67. myWatcher.PositionChanged += Watcher_PositionChanged;
  68. }
  69.  
  70. protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
  71. {
  72. if (App.Geolocator == null)
  73. {
  74. App.Geolocator = new Geolocator();
  75. App.Geolocator.DesiredAccuracy = PositionAccuracy.High;
  76. App.Geolocator.MovementThreshold = 100; // The units are meters.
  77. App.Geolocator.PositionChanged += geolocator_PositionChanged;
  78. }
  79. }
  80.  
  81. protected override void OnRemovedFromJournal(System.Windows.Navigation.JournalEntryRemovedEventArgs e)
  82. {
  83. App.Geolocator.PositionChanged -= geolocator_PositionChanged;
  84. App.Geolocator = null;
  85. }
  86.  
  87. void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
  88. {
  89. if (!App.RunningInBackground)
  90. {
  91. Dispatcher.BeginInvoke(() =>
  92. {
  93. LatitudeTextBlock.Text = args.Position.Coordinate.Latitude.ToString("0.00");
  94. LongitudeTextBlock.Text = args.Position.Coordinate.Longitude.ToString("0.00");
  95. });
  96. }
  97. else
  98. {
  99. Microsoft.Phone.Shell.ShellToast toast = new Microsoft.Phone.Shell.ShellToast();
  100. toast.Content = args.Position.Coordinate.Latitude.ToString("0.00");
  101. toast.Title = "Location: ";
  102. toast.NavigationUri = new Uri("/Page2.xaml", UriKind.Relative);
  103. toast.Show();
  104. }
  105. }
  106.  
  107. private void Timer_Tick(object sender, EventArgs e)
  108. {
  109. TimeSpan runTime = TimeSpan.FromMilliseconds(System.Environment.TickCount - _startTime);
  110. }
  111.  
  112.  
  113. private void StartButton_Click(object sender, RoutedEventArgs e)
  114. {
  115. if (_timer.IsEnabled)
  116. {
  117. myWatcher.Stop();
  118. _timer.Stop();
  119. StartButton.Content = "Start";
  120. }
  121. else
  122. {
  123. myWatcher.Start();
  124. _timer.Start();
  125. _startTime = System.Environment.TickCount;
  126. StartButton.Content = "Stop";
  127. }
  128. }
  129.  
  130. private void Watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
  131. {
  132. var coord = new GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude);
  133.  
  134. myMap.Center = coord;
  135. line.Path.Add(coord);
  136. }
  137.  
  138. public bool getConsentStatus()
  139. {
  140. if (IsolatedStorageSettings.ApplicationSettings.Contains("LocationConsent"))
  141. {
  142. // User has already made a decision, just retrieve that decision.
  143. if (Convert.ToBoolean(IsolatedStorageSettings.
  144. ApplicationSettings["LocationConsent"]))
  145. {
  146. return Convert.ToBoolean(IsolatedStorageSettings.
  147. ApplicationSettings["LocationConsent"]);
  148. }
  149. else
  150. {
  151. MessageBoxResult result =
  152. MessageBox.Show(AppConstants.strYouHadChoosenNoLoc, "Location", MessageBoxButton.OKCancel);
  153.  
  154. if (result == MessageBoxResult.OK)
  155. {
  156. IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = true;
  157. }
  158. else
  159. {
  160. IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = false;
  161. }
  162.  
  163. IsolatedStorageSettings.ApplicationSettings.Save();
  164. return result == MessageBoxResult.OK;
  165. }
  166. }
  167. else
  168. {
  169. MessageBoxResult result =
  170. MessageBox.Show(AppConstants.strAppRequiresYourLoc,
  171. "Location",
  172. MessageBoxButton.OKCancel);
  173.  
  174. if (result == MessageBoxResult.OK)
  175. {
  176. IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = true;
  177. }
  178. else
  179. {
  180. IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = false;
  181. }
  182.  
  183. IsolatedStorageSettings.ApplicationSettings.Save();
  184. return result == MessageBoxResult.OK;
  185. }
  186. }
  187.  
  188. private void fetchUserLocation()
  189. {
  190. // The watcher variable was previously declared as type GeoCoordinateWatcher.
  191. if (watcher == null)
  192. {
  193. watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High); // using high accuracy
  194. watcher.MovementThreshold = 20; // use MovementThreshold to ignore noise in the signal
  195. watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
  196. }
  197. watcher.Start();
  198. }
  199.  
  200. void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
  201. {
  202.  
  203. currentLatitude = e.Position.Location.Latitude.ToString("0.000");
  204. currentLongitude = e.Position.Location.Longitude.ToString("0.000");
  205.  
  206. if (!isPosSet)
  207. {
  208. isPosSet = true;
  209. startGeoNamesAPICall();
  210. }
  211. }
  212.  
  213. private void startGeoNamesAPICall()
  214. {
  215. try
  216. {
  217. HttpWebRequest httpReq = (HttpWebRequest)HttpWebRequest.Create(new Uri(AppConstants.baseUri + "&lat=" + currentLatitude + "&lng=" + currentLongitude + "&username=" + AppConstants.strUserName + "&radius=" + AppConstants.strDefaultRadiusForWikiAPI + "&maxRows=" + AppConstants.strDefaultResultRowsForWikiAPI));
  218. httpReq.BeginGetResponse(HTTPWebRequestCallBack, httpReq);
  219. }
  220. catch (Exception ex)
  221. {
  222. MessageBox.Show(ex.Message);
  223. }
  224. }
  225.  
  226. private void HTTPWebRequestCallBack(IAsyncResult result)
  227. {
  228. string strResponse = "";
  229.  
  230. try
  231. {
  232. Dispatcher.BeginInvoke(() =>
  233. {
  234. try
  235. {
  236. HttpWebRequest httpRequest = (HttpWebRequest)result.AsyncState;
  237. WebResponse response = httpRequest.EndGetResponse(result);
  238. Stream stream = response.GetResponseStream();
  239. StreamReader reader = new StreamReader(stream);
  240. strResponse = reader.ReadToEnd();
  241.  
  242. parseResponseData(strResponse);
  243. }
  244. catch (Exception ex)
  245. {
  246. MessageBox.Show(ex.Message);
  247. }
  248. });
  249. }
  250. catch (Exception ex)
  251. {
  252. MessageBox.Show(ex.Message);
  253. }
  254. }
  255.  
  256. private void parseResponseData(String aResponse)
  257. {
  258. placesListObj = new PlacesList();
  259.  
  260. MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(aResponse));
  261. DataContractJsonSerializer ser = new DataContractJsonSerializer(placesListObj.GetType());
  262. placesListObj = ser.ReadObject(ms) as PlacesList;
  263. ms.Close();
  264.  
  265. // updating UI
  266. if (placesListObj != null)
  267. {
  268. updateMap(placesListObj);
  269. }
  270. }
  271.  
  272. private void updateMap(PlacesList aWiKIAPIResponse)
  273. {
  274. int totalRecords = aWiKIAPIResponse.PlaceList.Count();
  275. myMap.Visibility = System.Windows.Visibility.Visible;
  276.  
  277. try
  278. {
  279. ObservableCollection<PlaceToMap> placeToMapObjs = new ObservableCollection<PlaceToMap>();
  280. for (int index = 0; index < totalRecords; index++)
  281. {
  282. placeToMapObjs.Add(new PlaceToMap()
  283. {
  284. Coordinate = new GeoCoordinate(Convert.ToDouble(aWiKIAPIResponse.PlaceList.ElementAt(index).Latitude),
  285. Convert.ToDouble(aWiKIAPIResponse.PlaceList.ElementAt(index).Longitude)),
  286. Info = aWiKIAPIResponse.PlaceList.ElementAt(index).Title + Environment.NewLine + aWiKIAPIResponse.PlaceList.ElementAt(index).Feature
  287. });
  288. }
  289.  
  290. ObservableCollection<DependencyObject> children = MapExtensions.GetChildren(myMap);
  291. var obj = children.FirstOrDefault(x => x.GetType() == typeof(MapItemsControl)) as MapItemsControl;
  292.  
  293. obj.ItemsSource = placeToMapObjs;
  294. myMap.SetView(new GeoCoordinate(Convert.ToDouble(currentLatitude), Convert.ToDouble(currentLongitude)), 14, 0, 55);
  295. }
  296. catch (Exception)
  297. {
  298.  
  299. }
  300. }
  301. }
  302. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement