MapsPanel.xaml.cs 33 KB

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