MapsPanel.xaml.cs 34 KB

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