MapsPanel.xaml.cs 33 KB

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