MapsPanel.xaml.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  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 System.Windows.Media;
  10. using Comal.Classes;
  11. using Comal.Stores;
  12. using InABox.Clients;
  13. using InABox.Configuration;
  14. using InABox.Core;
  15. using Syncfusion.UI.Xaml.Maps;
  16. namespace PRSDesktop
  17. {
  18. public class MapMarker
  19. {
  20. public Guid ID { get; set; }
  21. public string Latitude { get; set; }
  22. public string Longitude { get; set; }
  23. public string Code { get; set; }
  24. public string Description { get; set; }
  25. public DateTime Updated { get; set; }
  26. public string UpdatedBy { get; set; }
  27. public string DeviceID { get; set; }
  28. public Brush Background { get; internal set; }
  29. }
  30. public class ViewModel
  31. {
  32. private readonly List<MapMarker> _markers = new();
  33. private MapMarker _selected;
  34. public ViewModel()
  35. {
  36. Markers = new ObservableCollection<MapMarker>();
  37. }
  38. public ObservableCollection<MapMarker> Markers { get; }
  39. public MapMarker Selected
  40. {
  41. get => _selected;
  42. set
  43. {
  44. _selected = value;
  45. Refresh();
  46. }
  47. }
  48. public void Add(MapMarker marker, bool refresh = false)
  49. {
  50. _markers.Add(marker);
  51. if (refresh)
  52. Refresh();
  53. }
  54. public void Clear()
  55. {
  56. _selected = null;
  57. _markers.Clear();
  58. Refresh();
  59. }
  60. public void Refresh()
  61. {
  62. Markers.Clear();
  63. foreach (var marker in _markers)
  64. {
  65. marker.Background = new SolidColorBrush(marker == _selected ? Colors.Yellow : Colors.Orange);
  66. if (marker != _selected)
  67. Markers.Add(marker);
  68. }
  69. if (_selected != null)
  70. Markers.Add(_selected);
  71. }
  72. }
  73. public class ImageryLayerExt : ImageryLayer
  74. {
  75. protected override string GetUri(int X, int Y, int Scale)
  76. {
  77. var link = "http://mt1.google.com/vt/lyrs=y&x=" + X + "&y=" + Y + "&z=" + Scale;
  78. return link;
  79. }
  80. }
  81. public class GPSHistory
  82. {
  83. public DateTime Date { get; set; }
  84. public string Description { get; set; }
  85. public double Latitude { get; set; }
  86. public double Longitude { get; set; }
  87. }
  88. /// <summary>
  89. /// Interaction logic for MapsPanel.xaml
  90. /// </summary>
  91. public partial class MapsPanel : UserControl, IPanel<GPSTracker>
  92. {
  93. private LiveMapsSettings _settings;
  94. private bool bFirst = true;
  95. private readonly ViewModel viewmodel = new();
  96. private readonly int ZOOMEDIN = 16;
  97. public MapsPanel()
  98. {
  99. InitializeComponent();
  100. DataContext = viewmodel;
  101. //ausgov.Uri = "c:\\development\\maps\\MB_2011_WA.shp";
  102. }
  103. public bool IsReady { get; set; }
  104. public void CreateToolbarButtons(IPanelHost host)
  105. {
  106. }
  107. public string SectionName => "Maps";
  108. public DataModel DataModel(Selection selection)
  109. {
  110. return new MapsDataModel();
  111. }
  112. public void Heartbeat(TimeSpan time)
  113. {
  114. }
  115. public void Refresh()
  116. {
  117. var type = ViewType.SelectedItem as string;
  118. if (!string.IsNullOrWhiteSpace(type))
  119. {
  120. var grpid = ((KeyValuePair<Guid, string>)ViewGroup.SelectedItem).Key;
  121. if (type.Equals("Equipment"))
  122. {
  123. var filter = new Filter<Equipment>(x => x.TrackerLink.Location.Timestamp).IsNotEqualTo(DateTime.MinValue);
  124. if (!Security.IsAllowed<CanViewPrivateEquipment>())
  125. filter = filter.And(x => x.Private).IsEqualTo(false);
  126. if (grpid != Guid.Empty)
  127. filter = filter.And(x => x.GroupLink.ID).IsEqualTo(grpid);
  128. LoadMarkers(
  129. filter,
  130. x => x.ID,
  131. x => x.Code,
  132. x => x.Description,
  133. x => x.TrackerLink.DeviceID,
  134. x => x.TrackerLink.Location.Latitude,
  135. x => x.TrackerLink.Location.Longitude,
  136. x => x.TrackerLink.Description,
  137. x => x.TrackerLink.Location.Timestamp
  138. );
  139. }
  140. else if (type.Equals("Jobs"))
  141. {
  142. var filter = new Filter<Job>(x => x.SiteAddress.Location.Timestamp).IsNotEqualTo(DateTime.MinValue);
  143. if (grpid != Guid.Empty)
  144. filter = filter.And(x => x.JobStatus.ID).IsEqualTo(grpid);
  145. LoadMarkers(
  146. filter,
  147. x => x.ID,
  148. x => x.JobNumber,
  149. x => x.Name,
  150. null,
  151. x => x.SiteAddress.Location.Latitude,
  152. x => x.SiteAddress.Location.Longitude,
  153. x => x.LastUpdateBy,
  154. x => x.SiteAddress.Location.Timestamp
  155. );
  156. }
  157. else if (type.Equals("TimeSheets"))
  158. {
  159. if (grpid == Guid.Empty) // Starts
  160. LoadMarkers(
  161. new Filter<TimeSheet>(x => x.Date).IsEqualTo(DateTime.Today).And(x => x.StartLocation.Timestamp)
  162. .IsNotEqualTo(new TimeSpan(0)),
  163. x => x.EmployeeLink.ID,
  164. x => x.EmployeeLink.Code,
  165. x => x.EmployeeLink.Name,
  166. null,
  167. x => x.StartLocation.Latitude,
  168. x => x.StartLocation.Longitude,
  169. x => x.SoftwareVersion,
  170. x => x.StartLocation.Timestamp
  171. );
  172. else if (grpid == CoreUtils.FullGuid) // Finishes
  173. LoadMarkers(
  174. new Filter<TimeSheet>(x => x.Date).IsEqualTo(DateTime.Today).And(x => x.Finish).IsNotEqualTo(new TimeSpan(0))
  175. .And(x => x.FinishLocation.Timestamp).IsNotEqualTo(new TimeSpan(0)),
  176. x => x.EmployeeLink.ID,
  177. x => x.EmployeeLink.Code,
  178. x => x.EmployeeLink.Name,
  179. null,
  180. x => x.FinishLocation.Latitude,
  181. x => x.FinishLocation.Longitude,
  182. x => x.SoftwareVersion,
  183. x => x.FinishLocation.Timestamp
  184. );
  185. else // Open
  186. LoadMarkers(
  187. new Filter<TimeSheet>(x => x.Date).IsEqualTo(DateTime.Today).And(x => x.Finish).IsEqualTo(new TimeSpan(0))
  188. .And(x => x.StartLocation.Timestamp).IsNotEqualTo(new TimeSpan(0)),
  189. x => x.EmployeeLink.ID,
  190. x => x.EmployeeLink.Code,
  191. x => x.EmployeeLink.Name,
  192. null,
  193. x => x.StartLocation.Latitude,
  194. x => x.StartLocation.Longitude,
  195. x => x.SoftwareVersion,
  196. x => x.StartLocation.Timestamp
  197. );
  198. }
  199. else if (type.Equals("Trackers"))
  200. {
  201. var filter = new Filter<GPSTracker>(x => x.Location.Timestamp).IsNotEqualTo(DateTime.MinValue);
  202. if (grpid != Guid.Empty)
  203. filter = filter.And(x => x.Type.ID).IsEqualTo(grpid);
  204. LoadMarkers(
  205. filter,
  206. x => x.ID,
  207. x => x.DeviceID,
  208. x => x.Description,
  209. x => x.DeviceID,
  210. x => x.Location.Latitude,
  211. x => x.Location.Longitude,
  212. x => x.LastUpdateBy,
  213. x => x.Location.Timestamp
  214. );
  215. }
  216. }
  217. }
  218. public Dictionary<string, object[]> Selected()
  219. {
  220. return new Dictionary<string, object[]>();
  221. }
  222. public void Setup()
  223. {
  224. _settings = new UserConfiguration<LiveMapsSettings>().Load();
  225. if (ClientFactory.IsSupported<Equipment>())
  226. ViewType.Items.Add("Equipment");
  227. if (ClientFactory.IsSupported<Job>())
  228. ViewType.Items.Add("Jobs");
  229. if (ClientFactory.IsSupported<TimeSheet>())
  230. ViewType.Items.Add("TimeSheets");
  231. if (ClientFactory.IsSupported<GPSTracker>())
  232. ViewType.Items.Add("Trackers");
  233. ViewType.SelectedIndex = ViewType.Items.Count > _settings.ViewType ? _settings.ViewType : -1;
  234. ViewType.SelectionChanged += ViewTypeSelectionChanged;
  235. var groups = ViewType.SelectedIndex > -1 ? LoadGroups(ViewType.SelectedItem as string) : LoadGroups("");
  236. ViewGroup.ItemsSource = groups;
  237. ViewGroup.SelectedIndex = ViewGroup.Items.Count > _settings.ViewGroup ? _settings.ViewGroup : -1;
  238. ViewGroup.SelectionChanged += ViewGroupSelectionChanged;
  239. }
  240. public void Shutdown()
  241. {
  242. }
  243. public event DataModelUpdateEvent OnUpdateDataModel;
  244. public Dictionary<Type, CoreTable> DataEnvironment()
  245. {
  246. return new Dictionary<Type, CoreTable>();
  247. }
  248. private void LoadGroups<TGroup>(string all, Dictionary<Guid, string> results, Expression<Func<TGroup, string>> description)
  249. where TGroup : Entity, IRemotable, IPersistent, new()
  250. {
  251. results.Clear();
  252. results.Add(Guid.Empty, all);
  253. var groups = new Client<TGroup>().Query(
  254. LookupFactory.DefineFilter<TGroup>(),
  255. LookupFactory.DefineColumns<TGroup>(),
  256. LookupFactory.DefineSort<TGroup>()
  257. );
  258. foreach (var row in groups.Rows)
  259. results[row.Get<TGroup, Guid>(x => x.ID)] = row.Get(description);
  260. }
  261. private void ViewTypeSelectionChanged(object sender, SelectionChangedEventArgs e)
  262. {
  263. var sel = e.AddedItems.Count > 0 ? e.AddedItems[0] as string : null;
  264. if (string.IsNullOrWhiteSpace(sel))
  265. return;
  266. var groups = LoadGroups(sel);
  267. ViewGroup.SelectionChanged -= ViewGroupSelectionChanged;
  268. ViewGroup.ItemsSource = groups;
  269. ViewGroup.SelectionChanged += ViewGroupSelectionChanged;
  270. ViewGroup.SelectedIndex = groups.Any() ? 0 : -1;
  271. }
  272. private Dictionary<Guid, string> LoadGroups(string sel)
  273. {
  274. var result = new Dictionary<Guid, string>();
  275. if (sel.Equals("Equipment"))
  276. {
  277. LoadGroups<EquipmentGroup>("All Equipment", result, x => x.Description);
  278. }
  279. else if (sel.Equals("Jobs"))
  280. {
  281. LoadGroups<JobStatus>("All Jobs", result, x => x.Description);
  282. }
  283. else if (sel.Equals("TimeSheets"))
  284. {
  285. result[Guid.NewGuid()] = "Open TimeSheets";
  286. result[Guid.Empty] = "TimeSheet Starts";
  287. result[CoreUtils.FullGuid] = "TimeSheet Finishes";
  288. }
  289. else if (sel.Equals("Trackers"))
  290. {
  291. LoadGroups<GPSTrackerType>("All Trackers", result, x => x.Description);
  292. }
  293. return result;
  294. }
  295. private void ViewGroupSelectionChanged(object sender, SelectionChangedEventArgs e)
  296. {
  297. _settings.ViewType = ViewType.SelectedIndex;
  298. _settings.ViewGroup = ViewGroup.SelectedIndex;
  299. new UserConfiguration<LiveMapsSettings>().Save(_settings);
  300. Refresh();
  301. }
  302. private void LoadDayMarkers()
  303. {
  304. viewmodel.Markers.Clear();
  305. }
  306. private void LoadMarkers<T>(Filter<T> filter, Expression<Func<T, object>> guid, Expression<Func<T, object>> code,
  307. Expression<Func<T, object>> description, Expression<Func<T, object>> deviceid, Expression<Func<T, object>> latitude,
  308. Expression<Func<T, object>> longitude, Expression<Func<T, object>> updatedby, Expression<Func<T, object>> timestamp, bool first = true)
  309. where T : Entity, IRemotable, IPersistent, new()
  310. {
  311. viewmodel.Clear();
  312. var columns = new Columns<T>(guid, code, description, latitude, longitude, timestamp, updatedby);
  313. if (deviceid != null && !columns.ColumnNames().Contains(CoreUtils.GetFullPropertyName(deviceid, ".")))
  314. columns.Add(deviceid);
  315. new Client<T>().Query(
  316. filter,
  317. columns,
  318. null,
  319. (table, error) =>
  320. {
  321. Dispatcher.Invoke(() =>
  322. {
  323. viewmodel.Markers.Clear();
  324. if (error != null)
  325. {
  326. MessageBox.Show(error.Message);
  327. }
  328. else
  329. {
  330. var values = new Dictionary<Guid, DbMarker>();
  331. foreach (var row in table.Rows)
  332. {
  333. var id = (Guid)row.Get(guid);
  334. var time = (DateTime)row.Get(timestamp);
  335. if (!values.ContainsKey(id) || (first ? values[id].TimeStamp < time : values[id].TimeStamp > time))
  336. values[id] = new DbMarker(
  337. code != null ? (string)row.Get(code) : "",
  338. (string)row.Get(description),
  339. time,
  340. (double)row.Get(latitude),
  341. (double)row.Get(longitude),
  342. (string)row.Get(updatedby),
  343. deviceid != null ? (string)row.Get(deviceid) : ""
  344. );
  345. }
  346. foreach (var key in values.Keys)
  347. viewmodel.Add(
  348. new MapMarker
  349. {
  350. ID = key,
  351. Code = values[key].Code,
  352. Latitude = string.Format("{0:F6}", values[key].Latitude),
  353. Longitude = string.Format("{0:F6}", values[key].Longitude),
  354. Description = values[key].Description,
  355. Updated = values[key].TimeStamp,
  356. UpdatedBy = values[key].UpdatedBy,
  357. DeviceID = values[key].DeviceID
  358. }
  359. );
  360. viewmodel.Refresh();
  361. }
  362. //if (bFirst)
  363. ResetZoom();
  364. bFirst = false;
  365. LoadMarkerList();
  366. });
  367. }
  368. );
  369. }
  370. private void ResetZoom()
  371. {
  372. var nwLon = double.MaxValue;
  373. var nwLat = double.MinValue;
  374. var seLon = double.MinValue;
  375. var seLat = double.MaxValue;
  376. foreach (var marker in viewmodel.Markers)
  377. {
  378. var lat = double.Parse(marker.Latitude);
  379. var lon = double.Parse(marker.Longitude);
  380. if (lat != 0.0F && lon != 0.00)
  381. {
  382. nwLat = lat > nwLat ? lat : nwLat;
  383. seLat = lat < seLat ? lat : seLat;
  384. nwLon = lon < nwLon ? lon : nwLon;
  385. seLon = lon > seLon ? lon : seLon;
  386. }
  387. }
  388. var layer = Map.Layers[0] as ImageryLayer;
  389. var cLat = (nwLat + seLat) / 2.0F;
  390. var cLon = (nwLon + seLon) / 2.0F;
  391. layer.Center = new Point(cLat, cLon);
  392. layer.DistanceType = DistanceType.KiloMeter;
  393. var c = new Location { Latitude = cLat, Longitude = cLon };
  394. var nw = new Location { Latitude = nwLat, Longitude = nwLon };
  395. layer.Radius = c.DistanceTo(nw, UnitOfLength.Kilometers) / 2.0F;
  396. }
  397. private void ZoomIn_Click(object sender, RoutedEventArgs e)
  398. {
  399. CenterMap();
  400. if (Map.ZoomLevel < 20)
  401. {
  402. Map.ZoomLevel++;
  403. LoadMarkerList();
  404. }
  405. }
  406. private void ZoomOut_Click(object sender, RoutedEventArgs e)
  407. {
  408. CenterMap();
  409. if (Map.ZoomLevel > 1)
  410. {
  411. Map.ZoomLevel--;
  412. LoadMarkerList();
  413. }
  414. }
  415. private void Map_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
  416. {
  417. //CenterMap();
  418. if (e.Delta > 0)
  419. {
  420. if (Zoom.Value < 20)
  421. Zoom.Value++;
  422. e.Handled = true;
  423. }
  424. else if (e.Delta < 0)
  425. {
  426. if (Zoom.Value > 1)
  427. Zoom.Value--;
  428. e.Handled = true;
  429. }
  430. }
  431. private void CenterMap()
  432. {
  433. var layer = Map.Layers[0] as ImageryLayer;
  434. var center = layer.GetLatLonFromPoint(new Point(Map.ActualWidth / 2.0F, Map.ActualHeight / 2.0F));
  435. layer.Center = new Point(center.Y, center.X);
  436. }
  437. private void Map_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
  438. {
  439. var layer = Map.Layers[0] as ImageryLayer;
  440. var center = layer.GetLatLonFromPoint(e.GetPosition(Map));
  441. layer.Center = new Point(center.Y, center.X);
  442. if (Map.ZoomLevel < 20)
  443. {
  444. Map.ZoomLevel++;
  445. LoadMarkerList();
  446. }
  447. e.Handled = true;
  448. }
  449. private void Image_PreviewMouseDown(object sender, MouseButtonEventArgs e)
  450. {
  451. var border = sender as Border;
  452. //Point pBorder = border.TransformToAncestor(Map).Transform(new Point(0, 0));
  453. //var left = pBorder.X - 2;
  454. //var top = pBorder.Y - 2;
  455. //var right = left + border.ActualWidth + 4;
  456. //var bottom = top + border.ActualHeight + 4;
  457. //ImageryLayer layer = Map.Layers[0] as ImageryLayer;
  458. //var nw = layer.GetLatLonFromPoint(new Point(left, top));
  459. //var se = layer.GetLatLonFromPoint(new Point(right, bottom));
  460. var found = border.DataContext as MapMarker;
  461. Markers.SelectedItem = found;
  462. if (e.ClickCount > 1 && e.ButtonState == MouseButtonState.Pressed && e.ChangedButton == MouseButton.Left)
  463. ZoomToMarker(found);
  464. //foreach (var marker in viewmodel.Markers)
  465. //{
  466. // if (IsMarkerVisible(marker, nw, se))
  467. // {
  468. // found = marker;
  469. // break;
  470. // }
  471. //}
  472. //if (found != null)
  473. //{
  474. // Description.Text = found.Description;
  475. // LastUpdate.Text = String.Format("{0:dd MMM yy hh:mm:ss}", found.Updated);
  476. // Device.Text = found.UpdatedBy;
  477. // History.Visibility = String.IsNullOrWhiteSpace(found.DeviceID) ? Visibility.Collapsed : Visibility.Visible;
  478. // LoadDeviceHistory(found.DeviceID);
  479. // viewmodel.Selected = found;
  480. //}
  481. //else
  482. //{
  483. // Description.Text = "";
  484. // LastUpdate.Text = "";
  485. // Device.Text = "";
  486. // History.Visibility = Visibility.Collapsed;
  487. //}
  488. }
  489. private void Date_DateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  490. {
  491. var marker = Markers.SelectedItem as MapMarker;
  492. if (marker == null)
  493. return;
  494. LoadDeviceHistory(marker.DeviceID);
  495. }
  496. private void LoadDeviceHistory(string deviceID)
  497. {
  498. History.ItemsSource = null;
  499. var movements = new ObservableCollection<GPSHistory>();
  500. History.ItemsSource = movements;
  501. new Client<GPSTrackerLocation>().Query(
  502. new Filter<GPSTrackerLocation>(x => x.DeviceID).IsEqualTo(deviceID)
  503. .And(x => x.Location.Timestamp).IsGreaterThanOrEqualTo(Date.Date.Date)
  504. .And(x => x.Location.Timestamp).IsLessThan(Date.Date.Date.AddDays(1)),
  505. null,
  506. new SortOrder<GPSTrackerLocation>(x => x.Location.Timestamp, SortDirection.Descending),
  507. (table, error) =>
  508. {
  509. if (table != null)
  510. {
  511. var updates = new List<GPSTrackerLocation>();
  512. var last = new Location { Latitude = 0.0F, Longitude = 0.0F };
  513. var q = new List<CoreRow>();
  514. for (var i = 0; i < Math.Min(3, table.Rows.Count); i++)
  515. q.Add(table.Rows[i]);
  516. if (q.Count > 0)
  517. AddHistory(movements, updates, q[0]);
  518. for (var i = 3; i < table.Rows.Count; i++)
  519. {
  520. if (Moved(q, 0, 1) || Moved(q, 1, 2))
  521. AddHistory(movements, updates, q[1]);
  522. // Slide the window up
  523. q.RemoveAt(0);
  524. q.Add(table.Rows[i]);
  525. }
  526. // If there are only two records in the table,
  527. // make sure we add the second
  528. if (q.Count == 2)
  529. AddHistory(movements, updates, q[1]);
  530. // if there are three or more records,
  531. // make sure we add the last
  532. if (Moved(q, 2, 3))
  533. AddHistory(movements, updates, q[2]);
  534. //foreach (var row in table.Rows)
  535. //{
  536. // 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) };
  537. // if ((cur.Latitude != 0.0F) && (cur.Longitude != 0.0F)) // && (cur.DistanceTo(last, UnitOfLength.Kilometers) * 1000F > 500F))
  538. // {
  539. // AddHistory(movements, updates, row);
  540. // last = cur;
  541. // }
  542. //}
  543. if (updates.Any())
  544. new Client<GPSTrackerLocation>().Save(updates, "", (o, e) => { });
  545. if (!movements.Any())
  546. {
  547. var history = new GPSHistory
  548. {
  549. Date = DateTime.Today,
  550. Description = "No Activity Recorded",
  551. Latitude = 0.0F,
  552. Longitude = 0.0F
  553. };
  554. Dispatcher.Invoke(() => { movements.Add(history); });
  555. }
  556. }
  557. }
  558. );
  559. }
  560. private bool Moved(List<CoreRow> rows, int row1, int row2)
  561. {
  562. if (rows.Count <= row1)
  563. return false;
  564. if (rows.Count <= row2)
  565. return false;
  566. //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) };
  567. //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) };
  568. //return c1.DistanceTo(c0, UnitOfLength.Kilometers) * 1000F > 25F;
  569. var bDate = DateTime.Equals(
  570. rows[row1].Get<GPSTrackerLocation, DateTime>(x => x.Created).Date,
  571. rows[row2].Get<GPSTrackerLocation, DateTime>(x => x.Created).Date
  572. );
  573. var bAddress = string.Equals(
  574. rows[row1].Get<GPSTrackerLocation, string>(x => x.Location.Address),
  575. rows[row2].Get<GPSTrackerLocation, string>(x => x.Location.Address)
  576. );
  577. return /* !bDate || */ !bAddress;
  578. }
  579. private void AddHistory(ObservableCollection<GPSHistory> movements, List<GPSTrackerLocation> updates, CoreRow row)
  580. {
  581. var cur = new Location
  582. {
  583. Latitude = row.Get<GPSTrackerLocation, double>(x => x.Location.Latitude),
  584. Longitude = row.Get<GPSTrackerLocation, double>(x => x.Location.Longitude)
  585. };
  586. var address = row.Get<GPSTrackerLocation, string>(x => x.Location.Address);
  587. if (string.IsNullOrWhiteSpace(address))
  588. {
  589. address = StoreUtils.ReverseGeocode(cur.Latitude, cur.Longitude);
  590. var update = row.ToObject<GPSTrackerLocation>();
  591. update.Location.Address = address;
  592. updates.Add(update);
  593. }
  594. var history = new GPSHistory
  595. {
  596. Date = row.Get<GPSTrackerLocation, DateTime>(x => x.Location.Timestamp),
  597. Description = address,
  598. Latitude = cur.Latitude,
  599. Longitude = cur.Longitude
  600. };
  601. Dispatcher.Invoke(() => { movements.Add(history); });
  602. }
  603. private static bool IsMarkerVisible(MapMarker marker, Point northwest, Point southeast)
  604. {
  605. if (northwest.X == 0 && northwest.Y == 0)
  606. return true;
  607. var lat = double.Parse(marker.Latitude);
  608. var lon = double.Parse(marker.Longitude);
  609. var lat1 = northwest.Y < 0 ? lat <= northwest.Y : lat > northwest.Y;
  610. var lat2 = southeast.Y < 0 ? lat >= southeast.Y : lat <= southeast.Y;
  611. var lon1 = northwest.X < 0 ? lon <= northwest.X : lon > northwest.X;
  612. var lon2 = southeast.X < 0 ? lon >= southeast.X : lon <= southeast.X;
  613. return lat1 && lat2 && lon1 && lon2;
  614. }
  615. private void LoadMarkerList()
  616. {
  617. //var timer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(1) };
  618. //timer.Tick += ((t,e) =>
  619. //{
  620. //timer.IsEnabled = false;
  621. viewmodel.Refresh();
  622. var layer = Map.Layers[0] as ImageryLayer;
  623. var nw = layer.GetLatLonFromPoint(new Point(0F, 0F));
  624. var se = layer.GetLatLonFromPoint(new Point(Map.ActualWidth, Map.ActualHeight));
  625. var markers = viewmodel.Markers.Where(marker => ShowAll.IsChecked == true ? true : IsMarkerVisible(marker, nw, se))
  626. .OrderBy(x => x.Description);
  627. Markers.ItemsSource = markers.ToArray();
  628. //});
  629. //timer.IsEnabled = true;
  630. }
  631. private void Map_PreviewMouseUp(object sender, MouseButtonEventArgs e)
  632. {
  633. LoadMarkerList();
  634. }
  635. private void Markers_MouseDoubleClick(object sender, MouseButtonEventArgs e)
  636. {
  637. var marker = Markers.SelectedItem as MapMarker;
  638. ZoomToMarker(marker);
  639. }
  640. private void ZoomToMarker(MapMarker marker)
  641. {
  642. if (double.Parse(marker.Latitude) != 0.0F && double.Parse(marker.Longitude) != 0.0F)
  643. {
  644. var layer = Map.Layers[0] as ImageryLayer;
  645. layer.Center = new Point(double.Parse(marker.Latitude), double.Parse(marker.Longitude));
  646. Map.ZoomLevel = ZOOMEDIN;
  647. }
  648. }
  649. private void Markers_SelectionChanged(object sender, SelectionChangedEventArgs e)
  650. {
  651. var marker = Markers.SelectedItem as MapMarker;
  652. viewmodel.Selected = Markers.SelectedItem as MapMarker;
  653. if (marker != null)
  654. {
  655. Description.Text = marker.Description;
  656. LastUpdate.Text = string.Format("{0:dd MMM yy hh:mm:ss}", marker.Updated);
  657. Device.Text = marker.UpdatedBy;
  658. History.Visibility = string.IsNullOrWhiteSpace(marker.DeviceID) ? Visibility.Collapsed : Visibility.Visible;
  659. LoadDeviceHistory(marker.DeviceID);
  660. }
  661. else
  662. {
  663. Description.Text = "";
  664. LastUpdate.Text = "";
  665. Device.Text = "";
  666. History.Visibility = Visibility.Collapsed;
  667. }
  668. }
  669. private void Viewstyle_SelectionChanged(object sender, SelectionChangedEventArgs e)
  670. {
  671. var layer = typeof(ImageryLayer);
  672. var type = LayerType.OSM;
  673. var style = BingMapStyle.Road;
  674. if (Viewstyle.SelectedItem == BingStandardViewStyle)
  675. {
  676. layer = typeof(ImageryLayer);
  677. type = LayerType.Bing;
  678. style = BingMapStyle.Road;
  679. }
  680. else if (Viewstyle.SelectedItem == BingTerrainViewStyle)
  681. {
  682. layer = typeof(ImageryLayer);
  683. type = LayerType.Bing;
  684. style = BingMapStyle.Aerial;
  685. }
  686. else if (Viewstyle.SelectedItem == BingTerrainLabelsViewStyle)
  687. {
  688. layer = typeof(ImageryLayer);
  689. type = LayerType.Bing;
  690. style = BingMapStyle.AerialWithLabels;
  691. }
  692. else if (Viewstyle.SelectedItem == GoogleMapsViewStyle)
  693. {
  694. layer = typeof(ImageryLayerExt);
  695. }
  696. else
  697. {
  698. layer = typeof(ImageryLayer);
  699. type = LayerType.OSM;
  700. }
  701. var cur = Map.Layers[0] as ImageryLayer;
  702. if (!cur.GetType().Equals(layer))
  703. {
  704. var center = cur.Center;
  705. var radius = cur.Radius;
  706. var template = cur.MarkerTemplate;
  707. Map.Layers.Clear();
  708. if (layer == typeof(ImageryLayer))
  709. Map.Layers.Add(new ImageryLayer());
  710. else if (layer == typeof(ImageryLayerExt))
  711. Map.Layers.Add(new ImageryLayerExt());
  712. cur = Map.Layers[0] as ImageryLayer;
  713. cur.Center = center;
  714. cur.Radius = radius;
  715. cur.MarkerTemplate = template;
  716. cur.Markers = viewmodel.Markers;
  717. cur.BingMapKey = "5kn7uPPBBGKdmWYiwHJL~LjUY7IIgFzGdXpkpWT7Fsw~AmlksNuYOBHNQ3cOa61Nz2ghvK5EbrBZ3aQqvTS4OjcPxTBGNGsj2hKc058CgtgJ";
  718. }
  719. if (cur.LayerType != type)
  720. cur.LayerType = type;
  721. if (cur.BingMapStyle != style)
  722. cur.BingMapStyle = style;
  723. }
  724. private void IncludeVisibleMarkers_Checked(object sender, RoutedEventArgs e)
  725. {
  726. LoadMarkerList();
  727. }
  728. private void ResetView_Click(object sender, RoutedEventArgs e)
  729. {
  730. ResetZoom();
  731. }
  732. private void History_MouseDoubleClick(object sender, MouseButtonEventArgs e)
  733. {
  734. var history = History.SelectedItem as GPSHistory;
  735. if (history == null)
  736. return;
  737. if (history.Latitude != 0.0F && history.Longitude != 0.0F)
  738. {
  739. var layer = Map.Layers[0] as ImageryLayer;
  740. layer.Center = new Point(history.Latitude, history.Longitude);
  741. Map.ZoomLevel = ZOOMEDIN;
  742. }
  743. }
  744. private void Zoom_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
  745. {
  746. if (Map == null)
  747. return;
  748. Map.ZoomLevel = (int)e.NewValue;
  749. LoadMarkerList();
  750. }
  751. private class DbMarker
  752. {
  753. public DbMarker(string code, string description, DateTime timestamp, double latitude, double longitude, string updatedby, string deviceid)
  754. {
  755. Code = code;
  756. Description = description;
  757. TimeStamp = timestamp;
  758. Latitude = latitude;
  759. Longitude = longitude;
  760. UpdatedBy = updatedby;
  761. DeviceID = deviceid;
  762. }
  763. public string Code { get; }
  764. public string Description { get; }
  765. public DateTime TimeStamp { get; }
  766. public double Latitude { get; }
  767. public double Longitude { get; }
  768. public string UpdatedBy { get; }
  769. public string DeviceID { get; }
  770. }
  771. }
  772. }