MapsPanel.xaml.cs 34 KB

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