Gps.cs 2.8 KB

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