| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627 |
- using System;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Input;
- using Comal.Classes;
- using Comal.Stores;
- using InABox.Clients;
- using InABox.Configuration;
- using InABox.Core;
- using InABox.Wpf;
- using Syncfusion.UI.Xaml.Maps;
- using System.ComponentModel;
- using System.Drawing;
- using Point = System.Windows.Point;
- namespace PRSDesktop
- {
-
- public class GPSHistory
- {
- public DateTime Date { get; set; }
- public string Description { get; set; }
- public double Latitude { get; set; }
- public double Longitude { get; set; }
- }
- /// <summary>
- /// Interaction logic for MapsPanel.xaml
- /// </summary>
- public partial class MapsPanel : UserControl, IPanel<GPSTracker>
- {
- private LiveMapsSettings _settings;
- private bool bFirst = true;
- private readonly int ZOOMEDIN = 16;
- public MapsPanel()
- {
- InitializeComponent();
- }
- public bool IsReady { get; set; }
- public void CreateToolbarButtons(IPanelHost host)
- {
- }
- public string SectionName => "Maps";
- public DataModel DataModel(Selection selection)
- {
- return new MapsDataModel();
- }
- public void Heartbeat(TimeSpan time)
- {
- }
- public void Refresh()
- {
- ViewModel.Refresh();
- }
- public Dictionary<string, object[]> Selected()
- {
- return new Dictionary<string, object[]>();
- }
- public void Setup()
- {
- _settings = new UserConfiguration<LiveMapsSettings>().Load();
- ViewModel.Setup()
-
- ViewModel.
- ViewType.SelectionChanged += ViewTypeSelectionChanged;
-
- ViewModel.EntityGroup = _settings.EntityGroup
- var groups = ViewType.SelectedIndex > -1 ? LoadGroups(ViewType.SelectedItem as string) : LoadGroups("");
- ViewGroup.ItemsSource = groups;
- ViewGroup.SelectedIndex = ViewGroup.Items.Count > _settings.ViewGroup ? _settings.ViewGroup : -1;
- ViewGroup.SelectionChanged += ViewGroupSelectionChanged;
- }
- public void Shutdown(CancelEventArgs? cancel)
- {
- }
- public event DataModelUpdateEvent? OnUpdateDataModel;
- public Dictionary<Type, CoreTable> DataEnvironment()
- {
- return new Dictionary<Type, CoreTable>();
- }
- private void ViewTypeSelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- var sel = e.AddedItems.Count > 0 ? e.AddedItems[0] as string : null;
- if (string.IsNullOrWhiteSpace(sel))
- return;
- var groups = LoadGroups(sel);
- ViewGroup.SelectionChanged -= ViewGroupSelectionChanged;
- ViewGroup.ItemsSource = groups;
- ViewGroup.SelectionChanged += ViewGroupSelectionChanged;
- ViewGroup.SelectedIndex = groups.Any() ? 0 : -1;
- }
-
- private void ViewGroupSelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- _settings.ViewType = ViewType.SelectedIndex;
- _settings.ViewGroup = ViewGroup.SelectedIndex;
- new UserConfiguration<LiveMapsSettings>().Save(_settings);
- Refresh();
- }
- private void LoadDayMarkers()
- {
- ViewModel.Markers.Clear();
- }
- private void ResetZoom()
- {
- var nwLon = double.MaxValue;
- var nwLat = double.MinValue;
- var seLon = double.MinValue;
- var seLat = double.MaxValue;
- foreach (var marker in ViewModel.Markers)
- {
- var lat = double.Parse(marker.Latitude);
- var lon = double.Parse(marker.Longitude);
- if (lat != 0.0F && lon != 0.00)
- {
- nwLat = lat > nwLat ? lat : nwLat;
- seLat = lat < seLat ? lat : seLat;
- nwLon = lon < nwLon ? lon : nwLon;
- seLon = lon > seLon ? lon : seLon;
- }
- }
- var layer = Map.Layers[0] as ImageryLayer;
- var cLat = (nwLat + seLat) / 2.0F;
- var cLon = (nwLon + seLon) / 2.0F;
- layer.Center = new Point(cLat, cLon);
- layer.DistanceType = DistanceType.KiloMeter;
- var c = new Location { Latitude = cLat, Longitude = cLon };
- var nw = new Location { Latitude = nwLat, Longitude = nwLon };
- layer.Radius = c.DistanceTo(nw, UnitOfLength.Kilometers) / 2.0F;
- }
- private void ZoomIn_Click(object sender, RoutedEventArgs e)
- {
- CenterMap();
- if (Map.ZoomLevel < 20)
- {
- Map.ZoomLevel++;
- LoadMarkerList();
- }
- }
- private void ZoomOut_Click(object sender, RoutedEventArgs e)
- {
- CenterMap();
- if (Map.ZoomLevel > 1)
- {
- Map.ZoomLevel--;
- LoadMarkerList();
- }
- }
- private void Map_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
- {
- //CenterMap();
- if (e.Delta > 0)
- {
- if (Zoom.Value < 20)
- Zoom.Value++;
- e.Handled = true;
- }
- else if (e.Delta < 0)
- {
- if (Zoom.Value > 1)
- Zoom.Value--;
- e.Handled = true;
- }
- }
- private void CenterMap()
- {
- var layer = Map.Layers[0] as ImageryLayer;
- var center = layer.GetLatLonFromPoint(new Point(Map.ActualWidth / 2.0F, Map.ActualHeight / 2.0F));
- layer.Center = new Point(center.Y, center.X);
- }
- private void Map_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
- {
- var layer = Map.Layers[0] as ImageryLayer;
- var center = layer.GetLatLonFromPoint(e.GetPosition(Map));
- layer.Center = new Point(center.Y, center.X);
- if (Map.ZoomLevel < 20)
- {
- Map.ZoomLevel++;
- LoadMarkerList();
- }
- e.Handled = true;
- }
- private void Image_PreviewMouseDown(object sender, MouseButtonEventArgs e)
- {
- var border = sender as Border;
- //Point pBorder = border.TransformToAncestor(Map).Transform(new Point(0, 0));
- //var left = pBorder.X - 2;
- //var top = pBorder.Y - 2;
- //var right = left + border.ActualWidth + 4;
- //var bottom = top + border.ActualHeight + 4;
- //ImageryLayer layer = Map.Layers[0] as ImageryLayer;
- //var nw = layer.GetLatLonFromPoint(new Point(left, top));
- //var se = layer.GetLatLonFromPoint(new Point(right, bottom));
- var found = border.DataContext as MapMarker;
- Markers.SelectedItem = found;
- if (e.ClickCount > 1 && e.ButtonState == MouseButtonState.Pressed && e.ChangedButton == MouseButton.Left)
- ZoomToMarker(found);
- //foreach (var marker in viewmodel.Markers)
- //{
- // if (IsMarkerVisible(marker, nw, se))
- // {
- // found = marker;
- // break;
- // }
- //}
- //if (found != null)
- //{
- // Description.Text = found.Description;
- // LastUpdate.Text = String.Format("{0:dd MMM yy hh:mm:ss}", found.Updated);
- // Device.Text = found.UpdatedBy;
- // History.Visibility = String.IsNullOrWhiteSpace(found.DeviceID) ? Visibility.Collapsed : Visibility.Visible;
- // LoadDeviceHistory(found.DeviceID);
- // viewmodel.Selected = found;
- //}
- //else
- //{
- // Description.Text = "";
- // LastUpdate.Text = "";
- // Device.Text = "";
- // History.Visibility = Visibility.Collapsed;
- //}
- }
- private void Date_DateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
- {
- var marker = Markers.SelectedItem as MapMarker;
- if (marker == null)
- return;
- LoadDeviceHistory(marker.DeviceID);
- }
-
- private class WayPoint
- {
- public PointF Location { get; set; }
- public DateTime From { get; set; }
- public DateTime To { get; set; }
- }
- private void LoadDeviceHistory(string deviceID)
- {
-
- new Client<GPSTrackerLocation>().Query(
- new Filter<GPSTrackerLocation>(x => x.DeviceID).IsEqualTo(deviceID)
- .And(x => x.Location.Timestamp).IsGreaterThanOrEqualTo(Date.Date.Date)
- .And(x => x.Location.Timestamp).IsLessThan(Date.Date.Date.AddDays(1)),
- null,
- new SortOrder<GPSTrackerLocation>(x => x.Location.Timestamp, SortDirection.Descending),
- (table, error) =>
- {
-
- var movements = new ObservableCollection<GPSHistory>();
- if (table != null)
- {
- var updates = new List<GPSTrackerLocation>();
- var last = new Location { Latitude = 0.0F, Longitude = 0.0F };
- var q = new List<CoreRow>();
- for (var i = 0; i < Math.Min(3, table.Rows.Count); i++)
- q.Add(table.Rows[i]);
- if (q.Count > 0)
- AddHistory(movements, updates, q[0]);
- for (var i = 3; i < table.Rows.Count; i++)
- {
- if (Moved(q, 0, 1) || Moved(q, 1, 2))
- AddHistory(movements, updates, q[1]);
- // Slide the window up
- q.RemoveAt(0);
- q.Add(table.Rows[i]);
- }
- // If there are only two records in the table,
- // make sure we add the second
- if (q.Count == 2)
- AddHistory(movements, updates, q[1]);
- // if there are three or more records,
- // make sure we add the last
- if (Moved(q, 2, 3))
- AddHistory(movements, updates, q[2]);
- //foreach (var row in table.Rows)
- //{
- // 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) };
- // if ((cur.Latitude != 0.0F) && (cur.Longitude != 0.0F)) // && (cur.DistanceTo(last, UnitOfLength.Kilometers) * 1000F > 500F))
- // {
- // AddHistory(movements, updates, row);
- // last = cur;
- // }
- //}
- if (updates.Any())
- new Client<GPSTrackerLocation>().Save(updates, "", (o, e) => { });
- if (!movements.Any())
- {
- var history = new GPSHistory
- {
- Date = DateTime.Today,
- Description = "No Activity Recorded",
- Latitude = 0.0F,
- Longitude = 0.0F
- };
- movements.Add(history);
- }
- }
-
- List<WayPoint> waypoints = new List<WayPoint>();
- WayPoint? previous = null;
- foreach (var movement in movements.OrderBy(x=>x.Date))
- {
- var current = new PointF((float)movement.Longitude, (float)movement.Latitude);
-
- if (previous == null || Location.DistanceBetween(previous.Location, current, UnitOfLength.Kilometers) >= 0.05)
- {
- previous = new WayPoint()
- {
- Location = new PointF((float)movement.Longitude, (float)movement.Latitude),
- From = movement.Date,
- To = movement.Date
- };
- waypoints.Add(previous);
- }
- else
- previous.To = movement.Date;
- }
- Dispatcher.BeginInvoke(() =>
- {
- foreach (var waypoint in waypoints.Where(x=>x.To - x.From >= TimeSpan.FromMinutes(15)))
- {
- ViewModel.AddWayPoint(new MapMarker()
- {
- Label = $"{waypoint.From:h:mm}-{waypoint.To:h:mm}",
- Latitude = string.Format("{0:F6}", waypoint.Location.Y),
- Longitude = string.Format("{0:F6}", waypoint.Location.X),
- });
- }
- ViewModel.Refresh();
- History.ItemsSource = null;
- History.ItemsSource = movements;
- });
- }
- );
-
- }
- private bool Moved(List<CoreRow> rows, int row1, int row2)
- {
- if (rows.Count <= row1)
- return false;
- if (rows.Count <= row2)
- return false;
- //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) };
- //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) };
- //return c1.DistanceTo(c0, UnitOfLength.Kilometers) * 1000F > 25F;
- var bDate = DateTime.Equals(
- rows[row1].Get<GPSTrackerLocation, DateTime>(x => x.Created).Date,
- rows[row2].Get<GPSTrackerLocation, DateTime>(x => x.Created).Date
- );
- var bAddress = string.Equals(
- rows[row1].Get<GPSTrackerLocation, string>(x => x.Location.Address),
- rows[row2].Get<GPSTrackerLocation, string>(x => x.Location.Address)
- );
- return /* !bDate || */ !bAddress;
- }
- private void AddHistory(ObservableCollection<GPSHistory> movements, List<GPSTrackerLocation> updates, CoreRow row)
- {
- var cur = new Location
- {
- Latitude = row.Get<GPSTrackerLocation, double>(x => x.Location.Latitude),
- Longitude = row.Get<GPSTrackerLocation, double>(x => x.Location.Longitude)
- };
- var address = row.Get<GPSTrackerLocation, string>(x => x.Location.Address);
- if (string.IsNullOrWhiteSpace(address))
- {
- address = StoreUtils.ReverseGeocode(cur.Latitude, cur.Longitude);
- var update = row.ToObject<GPSTrackerLocation>();
- update.Location.Address = address;
- updates.Add(update);
- }
- var history = new GPSHistory
- {
- Date = row.Get<GPSTrackerLocation, DateTime>(x => x.Location.Timestamp),
- Description = address,
- Latitude = cur.Latitude,
- Longitude = cur.Longitude
- };
- Dispatcher.Invoke(() => { movements.Add(history); });
- }
- private static bool IsMarkerVisible(MapMarker marker, Point northwest, Point southeast)
- {
- if (northwest.X == 0 && northwest.Y == 0)
- return true;
- var lat = double.Parse(marker.Latitude);
- var lon = double.Parse(marker.Longitude);
- var lat1 = northwest.Y < 0 ? lat <= northwest.Y : lat > northwest.Y;
- var lat2 = southeast.Y < 0 ? lat >= southeast.Y : lat <= southeast.Y;
- var lon1 = northwest.X < 0 ? lon <= northwest.X : lon > northwest.X;
- var lon2 = southeast.X < 0 ? lon >= southeast.X : lon <= southeast.X;
- return lat1 && lat2 && lon1 && lon2;
- }
- private void LoadMarkerList()
- {
- //var timer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(1) };
- //timer.Tick += ((t,e) =>
- //{
- //timer.IsEnabled = false;
- ViewModel.Refresh();
- var layer = Map.Layers[0] as ImageryLayer;
- var nw = layer.GetLatLonFromPoint(new Point(0F, 0F));
- var se = layer.GetLatLonFromPoint(new Point(Map.ActualWidth, Map.ActualHeight));
- var markers = ViewModel.Markers.Where(marker => ShowAll.IsChecked == true ? true : IsMarkerVisible(marker, nw, se))
- .OrderBy(x => x.Description);
- Markers.ItemsSource = markers.ToArray();
- //});
- //timer.IsEnabled = true;
- }
- private void Map_PreviewMouseUp(object sender, MouseButtonEventArgs e)
- {
- LoadMarkerList();
- }
- private void Markers_MouseDoubleClick(object sender, MouseButtonEventArgs e)
- {
- var marker = Markers.SelectedItem as MapMarker;
- ZoomToMarker(marker);
- }
- private void ZoomToMarker(MapMarker marker)
- {
- if (marker == null)
- return;
-
- if (double.Parse(marker.Latitude) != 0.0F && double.Parse(marker.Longitude) != 0.0F)
- {
- var layer = Map.Layers[0] as ImageryLayer;
- layer.Center = new Point(double.Parse(marker.Latitude), double.Parse(marker.Longitude));
- Map.ZoomLevel = ZOOMEDIN;
- }
- }
- private void Markers_SelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- var marker = Markers.SelectedItem as MapMarker;
- ViewModel.Selected = Markers.SelectedItem as MapMarker;
- if (marker != null)
- {
- Description.Text = marker.Description;
- LastUpdate.Text = string.Format("{0:dd MMM yy hh:mm:ss}", marker.Updated);
- Device.Text = marker.UpdatedBy;
- History.Visibility = string.IsNullOrWhiteSpace(marker.DeviceID) ? Visibility.Collapsed : Visibility.Visible;
- LoadDeviceHistory(marker.DeviceID);
- }
- else
- {
- Description.Text = "";
- LastUpdate.Text = "";
- Device.Text = "";
- History.Visibility = Visibility.Collapsed;
- }
- }
- private void Viewstyle_SelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- var layer = typeof(ImageryLayer);
- var type = LayerType.OSM;
- var style = BingMapStyle.Road;
- if (Viewstyle.SelectedItem == BingStandardViewStyle)
- {
- layer = typeof(ImageryLayer);
- type = LayerType.Bing;
- style = BingMapStyle.Road;
- }
- else if (Viewstyle.SelectedItem == BingTerrainViewStyle)
- {
- layer = typeof(ImageryLayer);
- type = LayerType.Bing;
- style = BingMapStyle.Aerial;
- }
- else if (Viewstyle.SelectedItem == BingTerrainLabelsViewStyle)
- {
- layer = typeof(ImageryLayer);
- type = LayerType.Bing;
- style = BingMapStyle.AerialWithLabels;
- }
- else if (Viewstyle.SelectedItem == GoogleMapsViewStyle)
- {
- layer = typeof(GoogleImageryLayer);
- }
- else
- {
- layer = typeof(ImageryLayer);
- type = LayerType.OSM;
- }
- var cur = Map.Layers[0] as ImageryLayer;
- if (!cur.GetType().Equals(layer))
- {
- var center = cur.Center;
- var radius = cur.Radius;
- var template = cur.MarkerTemplate;
- Map.Layers.Clear();
- if (layer == typeof(ImageryLayer))
- Map.Layers.Add(new ImageryLayer());
- else if (layer == typeof(GoogleImageryLayer))
- Map.Layers.Add(new GoogleImageryLayer());
- cur = Map.Layers[0] as ImageryLayer;
- cur.Center = center;
- cur.Radius = radius;
- cur.MarkerTemplate = template;
- cur.Markers = ViewModel.Markers;
- cur.BingMapKey = "5kn7uPPBBGKdmWYiwHJL~LjUY7IIgFzGdXpkpWT7Fsw~AmlksNuYOBHNQ3cOa61Nz2ghvK5EbrBZ3aQqvTS4OjcPxTBGNGsj2hKc058CgtgJ";
- }
- if (cur.LayerType != type)
- cur.LayerType = type;
- if (cur.BingMapStyle != style)
- cur.BingMapStyle = style;
- }
- private void IncludeVisibleMarkers_Checked(object sender, RoutedEventArgs e)
- {
- LoadMarkerList();
- }
- private void ResetView_Click(object sender, RoutedEventArgs e)
- {
- ResetZoom();
- }
- private void History_MouseDoubleClick(object sender, MouseButtonEventArgs e)
- {
- var history = History.SelectedItem as GPSHistory;
- if (history == null)
- return;
- if (history.Latitude != 0.0F && history.Longitude != 0.0F)
- {
- var layer = Map.Layers[0] as ImageryLayer;
- layer.Center = new Point(history.Latitude, history.Longitude);
- Map.ZoomLevel = ZOOMEDIN;
- }
- }
- private void Zoom_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
- {
- if (Map == null)
- return;
- Map.ZoomLevel = (int)e.NewValue;
- LoadMarkerList();
- }
-
- private void TabView_PageChanged(object sender, SelectionChangedEventArgs e)
- {
- ViewModel.View = TabView.SelectedIndex == 0
- ? LiveMapView.All
- : LiveMapView.Selected;
- // ImageryLayer.MarkerTemplate = TabView.SelectedIndex == 0
- // ? TryFindResource("MapMarkerTemplate") as DataTemplate
- // : TryFindResource("MapWayPointTemplate") as DataTemplate;
- }
- }
- }
|