MapsPanel.xaml.cs 34 KB

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