Gps.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using System;
  2. using System.Collections.Generic;
  3. using Windows.Devices.AllJoyn;
  4. using Windows.Devices.Geolocation;
  5. using Windows.System;
  6. using Windows.UI.Xaml;
  7. using Breda_Tour.MapScreen;
  8. namespace Breda_Tour.Data
  9. {
  10. public class Gps
  11. {
  12. private MapPage mapPage;
  13. private Geolocator geolocator;
  14. private Geoposition _position;
  15. public Geoposition Position
  16. {
  17. get { return _position; }
  18. }
  19. public List<BasicGeoposition> History { get; set; }
  20. private PositionStatus _status;
  21. public PositionStatus Status
  22. {
  23. get { return _status; }
  24. }
  25. public Gps(MapPage mapPage)
  26. {
  27. History = new List<BasicGeoposition>();
  28. this.mapPage = mapPage;
  29. }
  30. public async void Start()
  31. {
  32. var accessStatus = await Geolocator.RequestAccessAsync();
  33. switch (accessStatus)
  34. {
  35. case GeolocationAccessStatus.Allowed:
  36. geolocator = new Geolocator { DesiredAccuracyInMeters = 5, MovementThreshold = 2 };
  37. // Subscribe events
  38. geolocator.StatusChanged += OnStatusChanged;
  39. geolocator.PositionChanged += OnPositionChanged;
  40. // Get position
  41. _position = await geolocator.GetGeopositionAsync();
  42. break;
  43. case GeolocationAccessStatus.Denied:
  44. _status = PositionStatus.NotAvailable;
  45. geolocator = null;
  46. bool result = await Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-location"));
  47. Refresh();
  48. break;
  49. case GeolocationAccessStatus.Unspecified:
  50. _status = PositionStatus.NotAvailable;
  51. break;
  52. }
  53. }
  54. private void OnPositionChanged(Geolocator sender, PositionChangedEventArgs args)
  55. {
  56. _position = args.Position;
  57. mapPage.ShowLocaton(_position.Coordinate.Point);
  58. //For route history line
  59. BasicGeoposition BasicG = _position.Coordinate.Point.Position;
  60. History.Add(BasicG);
  61. if (History.Count >= 2)
  62. {
  63. mapPage.DrawWalkingPath(History);
  64. }
  65. }
  66. private void OnStatusChanged(Geolocator sender, StatusChangedEventArgs args)
  67. {
  68. if (args.Status == PositionStatus.Disabled)
  69. {
  70. _position = null;
  71. }
  72. }
  73. public async void Refresh()
  74. {
  75. if (geolocator == null)
  76. {
  77. Start();
  78. }
  79. else
  80. {
  81. _position = await geolocator.GetGeopositionAsync();
  82. }
  83. }
  84. }
  85. }