MapsPanel.xaml.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Linq;
  5. using System.Linq.Expressions;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Input;
  9. using Comal.Classes;
  10. using Comal.Stores;
  11. using InABox.Clients;
  12. using InABox.Configuration;
  13. using InABox.Core;
  14. using InABox.Wpf;
  15. using Syncfusion.UI.Xaml.Maps;
  16. using System.ComponentModel;
  17. using System.Drawing;
  18. using Point = System.Windows.Point;
  19. namespace PRSDesktop
  20. {
  21. public class GPSHistory
  22. {
  23. public DateTime Date { get; set; }
  24. public string Description { get; set; }
  25. public double Latitude { get; set; }
  26. public double Longitude { get; set; }
  27. }
  28. /// <summary>
  29. /// Interaction logic for MapsPanel.xaml
  30. /// </summary>
  31. public partial class MapsPanel : UserControl, IPanel<GPSTracker>
  32. {
  33. private LiveMapsSettings _settings;
  34. private bool bFirst = true;
  35. private readonly int ZOOMEDIN = 16;
  36. public MapsPanel()
  37. {
  38. InitializeComponent();
  39. }
  40. public bool IsReady { get; set; }
  41. public void CreateToolbarButtons(IPanelHost host)
  42. {
  43. }
  44. public string SectionName => "Maps";
  45. public DataModel DataModel(Selection selection)
  46. {
  47. return new MapsDataModel();
  48. }
  49. public void Heartbeat(TimeSpan time)
  50. {
  51. }
  52. public void Refresh()
  53. {
  54. ViewModel.Refresh();
  55. }
  56. public Dictionary<string, object[]> Selected()
  57. {
  58. return new Dictionary<string, object[]>();
  59. }
  60. public void Setup()
  61. {
  62. _settings = new UserConfiguration<LiveMapsSettings>().Load();
  63. ViewModel.Setup()
  64. ViewModel.
  65. ViewType.SelectionChanged += ViewTypeSelectionChanged;
  66. ViewModel.EntityGroup = _settings.EntityGroup
  67. var groups = ViewType.SelectedIndex > -1 ? LoadGroups(ViewType.SelectedItem as string) : LoadGroups("");
  68. ViewGroup.ItemsSource = groups;
  69. ViewGroup.SelectedIndex = ViewGroup.Items.Count > _settings.ViewGroup ? _settings.ViewGroup : -1;
  70. ViewGroup.SelectionChanged += ViewGroupSelectionChanged;
  71. }
  72. public void Shutdown(CancelEventArgs? cancel)
  73. {
  74. }
  75. public event DataModelUpdateEvent? OnUpdateDataModel;
  76. public Dictionary<Type, CoreTable> DataEnvironment()
  77. {
  78. return new Dictionary<Type, CoreTable>();
  79. }
  80. private void ViewTypeSelectionChanged(object sender, SelectionChangedEventArgs e)
  81. {
  82. var sel = e.AddedItems.Count > 0 ? e.AddedItems[0] as string : null;
  83. if (string.IsNullOrWhiteSpace(sel))
  84. return;
  85. var groups = LoadGroups(sel);
  86. ViewGroup.SelectionChanged -= ViewGroupSelectionChanged;
  87. ViewGroup.ItemsSource = groups;
  88. ViewGroup.SelectionChanged += ViewGroupSelectionChanged;
  89. ViewGroup.SelectedIndex = groups.Any() ? 0 : -1;
  90. }
  91. private void ViewGroupSelectionChanged(object sender, SelectionChangedEventArgs e)
  92. {
  93. _settings.ViewType = ViewType.SelectedIndex;
  94. _settings.ViewGroup = ViewGroup.SelectedIndex;
  95. new UserConfiguration<LiveMapsSettings>().Save(_settings);
  96. Refresh();
  97. }
  98. private void LoadDayMarkers()
  99. {
  100. ViewModel.Markers.Clear();
  101. }
  102. private void ResetZoom()
  103. {
  104. var nwLon = double.MaxValue;
  105. var nwLat = double.MinValue;
  106. var seLon = double.MinValue;
  107. var seLat = double.MaxValue;
  108. foreach (var marker in ViewModel.Markers)
  109. {
  110. var lat = double.Parse(marker.Latitude);
  111. var lon = double.Parse(marker.Longitude);
  112. if (lat != 0.0F && lon != 0.00)
  113. {
  114. nwLat = lat > nwLat ? lat : nwLat;
  115. seLat = lat < seLat ? lat : seLat;
  116. nwLon = lon < nwLon ? lon : nwLon;
  117. seLon = lon > seLon ? lon : seLon;
  118. }
  119. }
  120. var layer = Map.Layers[0] as ImageryLayer;
  121. var cLat = (nwLat + seLat) / 2.0F;
  122. var cLon = (nwLon + seLon) / 2.0F;
  123. layer.Center = new Point(cLat, cLon);
  124. layer.DistanceType = DistanceType.KiloMeter;
  125. var c = new Location { Latitude = cLat, Longitude = cLon };
  126. var nw = new Location { Latitude = nwLat, Longitude = nwLon };
  127. layer.Radius = c.DistanceTo(nw, UnitOfLength.Kilometers) / 2.0F;
  128. }
  129. private void ZoomIn_Click(object sender, RoutedEventArgs e)
  130. {
  131. CenterMap();
  132. if (Map.ZoomLevel < 20)
  133. {
  134. Map.ZoomLevel++;
  135. LoadMarkerList();
  136. }
  137. }
  138. private void ZoomOut_Click(object sender, RoutedEventArgs e)
  139. {
  140. CenterMap();
  141. if (Map.ZoomLevel > 1)
  142. {
  143. Map.ZoomLevel--;
  144. LoadMarkerList();
  145. }
  146. }
  147. private void Map_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
  148. {
  149. //CenterMap();
  150. if (e.Delta > 0)
  151. {
  152. if (Zoom.Value < 20)
  153. Zoom.Value++;
  154. e.Handled = true;
  155. }
  156. else if (e.Delta < 0)
  157. {
  158. if (Zoom.Value > 1)
  159. Zoom.Value--;
  160. e.Handled = true;
  161. }
  162. }
  163. private void CenterMap()
  164. {
  165. var layer = Map.Layers[0] as ImageryLayer;
  166. var center = layer.GetLatLonFromPoint(new Point(Map.ActualWidth / 2.0F, Map.ActualHeight / 2.0F));
  167. layer.Center = new Point(center.Y, center.X);
  168. }
  169. private void Map_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
  170. {
  171. var layer = Map.Layers[0] as ImageryLayer;
  172. var center = layer.GetLatLonFromPoint(e.GetPosition(Map));
  173. layer.Center = new Point(center.Y, center.X);
  174. if (Map.ZoomLevel < 20)
  175. {
  176. Map.ZoomLevel++;
  177. LoadMarkerList();
  178. }
  179. e.Handled = true;
  180. }
  181. private void Image_PreviewMouseDown(object sender, MouseButtonEventArgs e)
  182. {
  183. var border = sender as Border;
  184. //Point pBorder = border.TransformToAncestor(Map).Transform(new Point(0, 0));
  185. //var left = pBorder.X - 2;
  186. //var top = pBorder.Y - 2;
  187. //var right = left + border.ActualWidth + 4;
  188. //var bottom = top + border.ActualHeight + 4;
  189. //ImageryLayer layer = Map.Layers[0] as ImageryLayer;
  190. //var nw = layer.GetLatLonFromPoint(new Point(left, top));
  191. //var se = layer.GetLatLonFromPoint(new Point(right, bottom));
  192. var found = border.DataContext as MapMarker;
  193. Markers.SelectedItem = found;
  194. if (e.ClickCount > 1 && e.ButtonState == MouseButtonState.Pressed && e.ChangedButton == MouseButton.Left)
  195. ZoomToMarker(found);
  196. //foreach (var marker in viewmodel.Markers)
  197. //{
  198. // if (IsMarkerVisible(marker, nw, se))
  199. // {
  200. // found = marker;
  201. // break;
  202. // }
  203. //}
  204. //if (found != null)
  205. //{
  206. // Description.Text = found.Description;
  207. // LastUpdate.Text = String.Format("{0:dd MMM yy hh:mm:ss}", found.Updated);
  208. // Device.Text = found.UpdatedBy;
  209. // History.Visibility = String.IsNullOrWhiteSpace(found.DeviceID) ? Visibility.Collapsed : Visibility.Visible;
  210. // LoadDeviceHistory(found.DeviceID);
  211. // viewmodel.Selected = found;
  212. //}
  213. //else
  214. //{
  215. // Description.Text = "";
  216. // LastUpdate.Text = "";
  217. // Device.Text = "";
  218. // History.Visibility = Visibility.Collapsed;
  219. //}
  220. }
  221. private void Date_DateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  222. {
  223. var marker = Markers.SelectedItem as MapMarker;
  224. if (marker == null)
  225. return;
  226. LoadDeviceHistory(marker.DeviceID);
  227. }
  228. private class WayPoint
  229. {
  230. public PointF Location { get; set; }
  231. public DateTime From { get; set; }
  232. public DateTime To { get; set; }
  233. }
  234. private void LoadDeviceHistory(string deviceID)
  235. {
  236. new Client<GPSTrackerLocation>().Query(
  237. new Filter<GPSTrackerLocation>(x => x.DeviceID).IsEqualTo(deviceID)
  238. .And(x => x.Location.Timestamp).IsGreaterThanOrEqualTo(Date.Date.Date)
  239. .And(x => x.Location.Timestamp).IsLessThan(Date.Date.Date.AddDays(1)),
  240. null,
  241. new SortOrder<GPSTrackerLocation>(x => x.Location.Timestamp, SortDirection.Descending),
  242. (table, error) =>
  243. {
  244. var movements = new ObservableCollection<GPSHistory>();
  245. if (table != null)
  246. {
  247. var updates = new List<GPSTrackerLocation>();
  248. var last = new Location { Latitude = 0.0F, Longitude = 0.0F };
  249. var q = new List<CoreRow>();
  250. for (var i = 0; i < Math.Min(3, table.Rows.Count); i++)
  251. q.Add(table.Rows[i]);
  252. if (q.Count > 0)
  253. AddHistory(movements, updates, q[0]);
  254. for (var i = 3; i < table.Rows.Count; i++)
  255. {
  256. if (Moved(q, 0, 1) || Moved(q, 1, 2))
  257. AddHistory(movements, updates, q[1]);
  258. // Slide the window up
  259. q.RemoveAt(0);
  260. q.Add(table.Rows[i]);
  261. }
  262. // If there are only two records in the table,
  263. // make sure we add the second
  264. if (q.Count == 2)
  265. AddHistory(movements, updates, q[1]);
  266. // if there are three or more records,
  267. // make sure we add the last
  268. if (Moved(q, 2, 3))
  269. AddHistory(movements, updates, q[2]);
  270. //foreach (var row in table.Rows)
  271. //{
  272. // InABox.Core.Location cur = new InABox.Core.Location() { Latitude = row.Get<GPSTrackerLocation, double>(x => x.Location.Latitude), Longitude = row.Get<GPSTrackerLocation, double>(x => x.Location.Longitude) };
  273. // if ((cur.Latitude != 0.0F) && (cur.Longitude != 0.0F)) // && (cur.DistanceTo(last, UnitOfLength.Kilometers) * 1000F > 500F))
  274. // {
  275. // AddHistory(movements, updates, row);
  276. // last = cur;
  277. // }
  278. //}
  279. if (updates.Any())
  280. new Client<GPSTrackerLocation>().Save(updates, "", (o, e) => { });
  281. if (!movements.Any())
  282. {
  283. var history = new GPSHistory
  284. {
  285. Date = DateTime.Today,
  286. Description = "No Activity Recorded",
  287. Latitude = 0.0F,
  288. Longitude = 0.0F
  289. };
  290. movements.Add(history);
  291. }
  292. }
  293. List<WayPoint> waypoints = new List<WayPoint>();
  294. WayPoint? previous = null;
  295. foreach (var movement in movements.OrderBy(x=>x.Date))
  296. {
  297. var current = new PointF((float)movement.Longitude, (float)movement.Latitude);
  298. if (previous == null || Location.DistanceBetween(previous.Location, current, UnitOfLength.Kilometers) >= 0.05)
  299. {
  300. previous = new WayPoint()
  301. {
  302. Location = new PointF((float)movement.Longitude, (float)movement.Latitude),
  303. From = movement.Date,
  304. To = movement.Date
  305. };
  306. waypoints.Add(previous);
  307. }
  308. else
  309. previous.To = movement.Date;
  310. }
  311. Dispatcher.BeginInvoke(() =>
  312. {
  313. foreach (var waypoint in waypoints.Where(x=>x.To - x.From >= TimeSpan.FromMinutes(15)))
  314. {
  315. ViewModel.AddWayPoint(new MapMarker()
  316. {
  317. Label = $"{waypoint.From:h:mm}-{waypoint.To:h:mm}",
  318. Latitude = string.Format("{0:F6}", waypoint.Location.Y),
  319. Longitude = string.Format("{0:F6}", waypoint.Location.X),
  320. });
  321. }
  322. ViewModel.Refresh();
  323. History.ItemsSource = null;
  324. History.ItemsSource = movements;
  325. });
  326. }
  327. );
  328. }
  329. private bool Moved(List<CoreRow> rows, int row1, int row2)
  330. {
  331. if (rows.Count <= row1)
  332. return false;
  333. if (rows.Count <= row2)
  334. return false;
  335. //InABox.Core.Location c0 = new InABox.Core.Location() { Latitude = rows[row1].Get<GPSTrackerLocation, double>(x => x.Location.Latitude), Longitude = rows[row1].Get<GPSTrackerLocation, double>(x => x.Location.Longitude) };
  336. //InABox.Core.Location c1 = new InABox.Core.Location() { Latitude = rows[row2].Get<GPSTrackerLocation, double>(x => x.Location.Latitude), Longitude = rows[row2].Get<GPSTrackerLocation, double>(x => x.Location.Longitude) };
  337. //return c1.DistanceTo(c0, UnitOfLength.Kilometers) * 1000F > 25F;
  338. var bDate = DateTime.Equals(
  339. rows[row1].Get<GPSTrackerLocation, DateTime>(x => x.Created).Date,
  340. rows[row2].Get<GPSTrackerLocation, DateTime>(x => x.Created).Date
  341. );
  342. var bAddress = string.Equals(
  343. rows[row1].Get<GPSTrackerLocation, string>(x => x.Location.Address),
  344. rows[row2].Get<GPSTrackerLocation, string>(x => x.Location.Address)
  345. );
  346. return /* !bDate || */ !bAddress;
  347. }
  348. private void AddHistory(ObservableCollection<GPSHistory> movements, List<GPSTrackerLocation> updates, CoreRow row)
  349. {
  350. var cur = new Location
  351. {
  352. Latitude = row.Get<GPSTrackerLocation, double>(x => x.Location.Latitude),
  353. Longitude = row.Get<GPSTrackerLocation, double>(x => x.Location.Longitude)
  354. };
  355. var address = row.Get<GPSTrackerLocation, string>(x => x.Location.Address);
  356. if (string.IsNullOrWhiteSpace(address))
  357. {
  358. address = StoreUtils.ReverseGeocode(cur.Latitude, cur.Longitude);
  359. var update = row.ToObject<GPSTrackerLocation>();
  360. update.Location.Address = address;
  361. updates.Add(update);
  362. }
  363. var history = new GPSHistory
  364. {
  365. Date = row.Get<GPSTrackerLocation, DateTime>(x => x.Location.Timestamp),
  366. Description = address,
  367. Latitude = cur.Latitude,
  368. Longitude = cur.Longitude
  369. };
  370. Dispatcher.Invoke(() => { movements.Add(history); });
  371. }
  372. private static bool IsMarkerVisible(MapMarker marker, Point northwest, Point southeast)
  373. {
  374. if (northwest.X == 0 && northwest.Y == 0)
  375. return true;
  376. var lat = double.Parse(marker.Latitude);
  377. var lon = double.Parse(marker.Longitude);
  378. var lat1 = northwest.Y < 0 ? lat <= northwest.Y : lat > northwest.Y;
  379. var lat2 = southeast.Y < 0 ? lat >= southeast.Y : lat <= southeast.Y;
  380. var lon1 = northwest.X < 0 ? lon <= northwest.X : lon > northwest.X;
  381. var lon2 = southeast.X < 0 ? lon >= southeast.X : lon <= southeast.X;
  382. return lat1 && lat2 && lon1 && lon2;
  383. }
  384. private void LoadMarkerList()
  385. {
  386. //var timer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(1) };
  387. //timer.Tick += ((t,e) =>
  388. //{
  389. //timer.IsEnabled = false;
  390. ViewModel.Refresh();
  391. var layer = Map.Layers[0] as ImageryLayer;
  392. var nw = layer.GetLatLonFromPoint(new Point(0F, 0F));
  393. var se = layer.GetLatLonFromPoint(new Point(Map.ActualWidth, Map.ActualHeight));
  394. var markers = ViewModel.Markers.Where(marker => ShowAll.IsChecked == true ? true : IsMarkerVisible(marker, nw, se))
  395. .OrderBy(x => x.Description);
  396. Markers.ItemsSource = markers.ToArray();
  397. //});
  398. //timer.IsEnabled = true;
  399. }
  400. private void Map_PreviewMouseUp(object sender, MouseButtonEventArgs e)
  401. {
  402. LoadMarkerList();
  403. }
  404. private void Markers_MouseDoubleClick(object sender, MouseButtonEventArgs e)
  405. {
  406. var marker = Markers.SelectedItem as MapMarker;
  407. ZoomToMarker(marker);
  408. }
  409. private void ZoomToMarker(MapMarker marker)
  410. {
  411. if (marker == null)
  412. return;
  413. if (double.Parse(marker.Latitude) != 0.0F && double.Parse(marker.Longitude) != 0.0F)
  414. {
  415. var layer = Map.Layers[0] as ImageryLayer;
  416. layer.Center = new Point(double.Parse(marker.Latitude), double.Parse(marker.Longitude));
  417. Map.ZoomLevel = ZOOMEDIN;
  418. }
  419. }
  420. private void Markers_SelectionChanged(object sender, SelectionChangedEventArgs e)
  421. {
  422. var marker = Markers.SelectedItem as MapMarker;
  423. ViewModel.Selected = Markers.SelectedItem as MapMarker;
  424. if (marker != null)
  425. {
  426. Description.Text = marker.Description;
  427. LastUpdate.Text = string.Format("{0:dd MMM yy hh:mm:ss}", marker.Updated);
  428. Device.Text = marker.UpdatedBy;
  429. History.Visibility = string.IsNullOrWhiteSpace(marker.DeviceID) ? Visibility.Collapsed : Visibility.Visible;
  430. LoadDeviceHistory(marker.DeviceID);
  431. }
  432. else
  433. {
  434. Description.Text = "";
  435. LastUpdate.Text = "";
  436. Device.Text = "";
  437. History.Visibility = Visibility.Collapsed;
  438. }
  439. }
  440. private void Viewstyle_SelectionChanged(object sender, SelectionChangedEventArgs e)
  441. {
  442. var layer = typeof(ImageryLayer);
  443. var type = LayerType.OSM;
  444. var style = BingMapStyle.Road;
  445. if (Viewstyle.SelectedItem == BingStandardViewStyle)
  446. {
  447. layer = typeof(ImageryLayer);
  448. type = LayerType.Bing;
  449. style = BingMapStyle.Road;
  450. }
  451. else if (Viewstyle.SelectedItem == BingTerrainViewStyle)
  452. {
  453. layer = typeof(ImageryLayer);
  454. type = LayerType.Bing;
  455. style = BingMapStyle.Aerial;
  456. }
  457. else if (Viewstyle.SelectedItem == BingTerrainLabelsViewStyle)
  458. {
  459. layer = typeof(ImageryLayer);
  460. type = LayerType.Bing;
  461. style = BingMapStyle.AerialWithLabels;
  462. }
  463. else if (Viewstyle.SelectedItem == GoogleMapsViewStyle)
  464. {
  465. layer = typeof(GoogleImageryLayer);
  466. }
  467. else
  468. {
  469. layer = typeof(ImageryLayer);
  470. type = LayerType.OSM;
  471. }
  472. var cur = Map.Layers[0] as ImageryLayer;
  473. if (!cur.GetType().Equals(layer))
  474. {
  475. var center = cur.Center;
  476. var radius = cur.Radius;
  477. var template = cur.MarkerTemplate;
  478. Map.Layers.Clear();
  479. if (layer == typeof(ImageryLayer))
  480. Map.Layers.Add(new ImageryLayer());
  481. else if (layer == typeof(GoogleImageryLayer))
  482. Map.Layers.Add(new GoogleImageryLayer());
  483. cur = Map.Layers[0] as ImageryLayer;
  484. cur.Center = center;
  485. cur.Radius = radius;
  486. cur.MarkerTemplate = template;
  487. cur.Markers = ViewModel.Markers;
  488. cur.BingMapKey = "5kn7uPPBBGKdmWYiwHJL~LjUY7IIgFzGdXpkpWT7Fsw~AmlksNuYOBHNQ3cOa61Nz2ghvK5EbrBZ3aQqvTS4OjcPxTBGNGsj2hKc058CgtgJ";
  489. }
  490. if (cur.LayerType != type)
  491. cur.LayerType = type;
  492. if (cur.BingMapStyle != style)
  493. cur.BingMapStyle = style;
  494. }
  495. private void IncludeVisibleMarkers_Checked(object sender, RoutedEventArgs e)
  496. {
  497. LoadMarkerList();
  498. }
  499. private void ResetView_Click(object sender, RoutedEventArgs e)
  500. {
  501. ResetZoom();
  502. }
  503. private void History_MouseDoubleClick(object sender, MouseButtonEventArgs e)
  504. {
  505. var history = History.SelectedItem as GPSHistory;
  506. if (history == null)
  507. return;
  508. if (history.Latitude != 0.0F && history.Longitude != 0.0F)
  509. {
  510. var layer = Map.Layers[0] as ImageryLayer;
  511. layer.Center = new Point(history.Latitude, history.Longitude);
  512. Map.ZoomLevel = ZOOMEDIN;
  513. }
  514. }
  515. private void Zoom_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
  516. {
  517. if (Map == null)
  518. return;
  519. Map.ZoomLevel = (int)e.NewValue;
  520. LoadMarkerList();
  521. }
  522. private void TabView_PageChanged(object sender, SelectionChangedEventArgs e)
  523. {
  524. ViewModel.View = TabView.SelectedIndex == 0
  525. ? LiveMapView.All
  526. : LiveMapView.Selected;
  527. // ImageryLayer.MarkerTemplate = TabView.SelectedIndex == 0
  528. // ? TryFindResource("MapMarkerTemplate") as DataTemplate
  529. // : TryFindResource("MapWayPointTemplate") as DataTemplate;
  530. }
  531. }
  532. }