-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMapPageViewModel.cs
3623 lines (2996 loc) · 154 KB
/
MapPageViewModel.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Collections.Generic;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
using System.Collections.ObjectModel;
using Windows.UI.Xaml;
using Windows.Devices.Geolocation;
using Windows.UI.Xaml.Controls;
using Windows.Storage;
using Windows.UI.Core;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.UI.Controls;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Data;
using GSCFieldApp.Services.DatabaseServices;
using GSCFieldApp.Models;
using GSCFieldApp.Dictionaries;
using Template10.Mvvm;
using Template10.Controls;
using Windows.ApplicationModel.Resources;
using Windows.System;
using Windows.UI.Xaml.Input;
using System.Globalization;
using Symbol = Windows.UI.Xaml.Controls.Symbol;
using Newtonsoft.Json;
using SQLite;
using GSCFieldApp.Services;
//Added by jamel
using ProjNet.CoordinateSystems;
using ProjNet.CoordinateSystems.Transformations;
using ProjNet.Converters.WellKnownText;
using ProjNet;
using GeoAPI.CoordinateSystems;
using GeoAPI.CoordinateSystems.Transformations;
using System.Diagnostics;
namespace GSCFieldApp.ViewModels
{
public class MapPageViewModel : ViewModelBase
{
#region INIT
//Map
public MapView currentMapView { get; set; }
public Map esriMap;
public double viewRotation = 0; //Default
private bool _noMapsWatermark = false;
private double mapScale = ApplicationLiterals.defaultMapScale;
//Layers
public ArcGISTiledLayer _basemapLayer;
public ArcGISTiledLayer _bLayer;
public string filepathname;
public Visibility canDeleteLayer = Visibility.Visible; //Default
public ArcGISTiledLayer defaultLayer;
private ObservableCollection<MapPageLayers> _filenameValues = new ObservableCollection<MapPageLayers>();
private object _selectedLayer;
public object selectedStationID = string.Empty; //Will be used to show report page on user identified station.
public object selectedStationDate = string.Empty; //Will be used to show report page on user identified station.
//Model and strings
private readonly DataAccess accessData = new DataAccess();
private readonly DataLocalSettings localSettings = new DataLocalSettings();
public FieldLocation locationModel = new FieldLocation();
//Other
public bool addDataDialogPopedUp = false; //Will be used to stop pop-up launching everytime user navigates to map page.
public ResourceLoader local = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();
readonly DataLocalSettings localSetting = new DataLocalSettings();
public DataIDCalculation idCalculator = new DataIDCalculation();
//Quick buttons
private bool _mapPageQuickSampleEnable = true;
private bool _mapPageQuickPhotoEnable = true;
private bool _mapPageQuickMeasurementEnable = true;
public string clickedQuickButton = string.Empty; //Will be used to track what user wants to tap option
//Progress ring
private bool _progressRingActive = false;
private bool _progressRingVisibility = false;
//GPS
public Geolocator _geolocator = null;
public Geoposition _currentMSGeoposition;
public bool userHasTurnedGPSOff = false;
public double _currentLongitude = 0.0;
public double _currentLatitude = 0.0;
public double _currentAltitude = 0.0;
public double _currentEasting = 0.0;
public double _currentNorthing = 0.0;
public double _currentAccuracy = 0.0;
public string _currentProjection = string.Empty; //Added by jamel to get projection info
public bool initializingGPS = false;
public bool _mapRingLabelAcquiringGPSVisibility = false;
public Symbol _GPSModeSymbol = Symbol.Target;
//Map Graphics
private readonly SimpleMarkerSymbol _posSym = new SimpleMarkerSymbol();
public GraphicsOverlay _OverlayStation;
public GraphicsOverlay _OverlayStationLabel;
public GraphicsOverlay _OverlayCurrentPosition;
public GraphicsOverlay _OverlayStructure;
public Dictionary<string, List<GraphicsOverlay>> _overlayContainerOther; //Will act as a "layer" container but for graphics, just like esriMap.Basemap.BaseLayers object
private System.Drawing.Color _accuracyColor = new System.Drawing.Color();
private SimpleFillSymbol _accSym = new SimpleFillSymbol();
private SimpleLineSymbol _accLineSym = new SimpleLineSymbol();
//private Graphic _accGraphic = null;
private MapPoint _centerPoint = new MapPoint(0, 0, 0.0, SpatialReferences.Wgs84);
private MapPoint _projectedCenterPoint = null;
//private Graphic _posGraphic = null;
public bool pauseGraphicRefresh = false;
//Delegates and events
public static event EventHandler newDataLoaded; //This event is triggered when a new data has been loaded
//Constants
public string attributeID = "ID";
public string attributeIDPosition = "Position";
public string attributeIDAccuracy = "PositionAccuracy";
//Testing
private bool initMap = false;
public MapPageViewModel()
{
//Init
lastTakenLocation = new Tuple<double, double>(0, 0);
_OverlayStation = new GraphicsOverlay();
_OverlayStationLabel = new GraphicsOverlay();
_overlayContainerOther = new Dictionary<string, List<GraphicsOverlay>>();
_OverlayStructure = new GraphicsOverlay();
//_OverlayCurrentPosition = new GraphicsOverlay();
CreatePositionGraphic();
//SetAccuracyGraphic();
//Detect addition of any new layers
newDataLoaded += ShellViewModel_newDataLoaded;
SettingsPageViewModel.settingDeleteAllLayers += SettingsPageViewModel_deleteAllLayers;
FieldBooksPageViewModel.deleteAllLayers += SettingsPageViewModel_deleteAllLayers;
//Detect new field book selection, uprgrade, edit, ...
FieldBooksPageViewModel.newFieldBookSelected -= FieldBooksPageViewModel_newFieldBookSelectedAsync;
FieldBooksPageViewModel.newFieldBookSelected += FieldBooksPageViewModel_newFieldBookSelectedAsync;
//Detect other setting events
SettingsPartViewModel.settingUseStructureSymbols += SettingsPartViewModel_settingUseStructureSymbols;
//Detect location edits
LocationViewModel.LocationUpdateEventHandler += LocationViewModel_LocationUpdateEventHandler;
//Set some configs
SetQuickButtonEnable();
//Fill vocab
FillLocationVocab();
}
private void EsriMap_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (!initMap)
{
initMap = true;
}
}
#endregion
#region PROPERTIES
public Dictionary<string, Dictionary<string, string>> _layerRendering { get; set; }
//public Dictionary<string, Tuple<string, bool, double>> _layerRenderingConfiguration { get; set; } //Will be used to show layer in proper order, visibility and opacity based on previous setting on app opening.
public Symbol GPSModeSymbol { get { return _GPSModeSymbol; } set { _GPSModeSymbol = value; } }
public bool NoMapsWatermark { get { return _noMapsWatermark; } set { _noMapsWatermark = value; } }
public ObservableCollection<MapPageLayers> FilenameValues { get { return _filenameValues; } set { _filenameValues = value; } }
public object SelectedLayer
{
get { return _selectedLayer; }
set
{
if (value != null)
{
_selectedLayer = value;
}
}
}
public Geoposition CurrentMSGeoposition { get { return _currentMSGeoposition; } set { _currentMSGeoposition = value; } }
public double CurrentLongitude { get { return _currentLongitude; } set { _currentLongitude = value; } }
public double CurrentLatitude { get { return _currentLatitude; } set { _currentLatitude = value; } }
public double CurrentAltitude { get { return _currentAltitude; } set { _currentAltitude = value; } }
public double CurrentEasting { get { return _currentEasting; } set { _currentEasting = value; } }
public double CurrentNorthing { get { return _currentNorthing; } set { _currentNorthing = value; } }
public double CurrentAccuracy { get { return _currentAccuracy; } set { _currentAccuracy = value; } }
public string CurrentProjection { get { return _currentProjection; } set { _currentProjection = value; } } //Added by Jamel
public Tuple<double, double> lastTakenLocation { get; set; }
public bool MapRingActive
{
get { return _progressRingActive; }
set { _progressRingActive = value; }
}
public bool MapRingVisibility
{
get { return _progressRingVisibility; }
set { _progressRingVisibility = value; }
}
public bool MapRingLabelAcquiringGPSVisibility
{
get { return _mapRingLabelAcquiringGPSVisibility; }
set { _mapRingLabelAcquiringGPSVisibility = value; }
}
//public bool GPSSignalReceptionVisibility { get { return _GPSSignalReceptionVisibility; } set { _GPSSignalReceptionVisibility = value; } }
public bool MapPageQuickMeasurementEnable { get { return _mapPageQuickMeasurementEnable; } set { _mapPageQuickMeasurementEnable = value; } }
public bool MapPageQuickPhotoEnable { get { return _mapPageQuickPhotoEnable; } set { _mapPageQuickPhotoEnable = value; } }
public bool MapPageQuickSampleEnable { get { return _mapPageQuickSampleEnable; } set { _mapPageQuickSampleEnable = value; } }
//Dictionary values
public string vocabEntryTypeTap { get; set; }
public string vocabEntryTypeGPS { get; set; }
public string vocabElevmethodGPS { get; set; }
public string vocabErrorMeasureTypeMeter { get; set; }
public string vocabEntryTypeManual { get; set; }
#endregion
#region MAP INTERACTION
/// <summary>
/// Will set layers, GPS and navigate to current location
/// </summary>
/// <param name="inMapView"></param>
/// <returns></returns>
public async Task SetMapView(MapView inMapView)
{
//PART 1. Load Map
// Create variable for use elsewhere in this class, maybe better way
if (currentMapView == null)
{
currentMapView = inMapView;
}
//Create new map if ncessary
if (esriMap == null)
{
#region Add layers
Task loadAll = AddAllLayers();
await loadAll;
#endregion
}
// PART 2. Deal with GPS
// spw2017
if (_currentMSGeoposition == null)
{
Task setGPSTask = SetGPS();
await setGPSTask;
}
//Set some configs
SetQuickButtonEnable();
}
/// <summary>
/// Will initialized the GPS
/// </summary>
/// <returns></returns>
public async Task SetGPS()
{
//// Location platform is attempting to acquire a fix.
//ResetLocationGraphic();
var accessStatus = await Geolocator.RequestAccessAsync();
switch (accessStatus)
{
case GeolocationAccessStatus.Allowed:
currentMapView.Tapped -= myMapView_AddByTap;
// If DesiredAccuracy or DesiredAccuracyInMeters are not set (or value is 0), DesiredAccuracy.Default is used.
_geolocator = new Geolocator { ReportInterval = 750 };
// Subscribe to the StatusChanged event to get updates of location status changes.
_geolocator.PositionChanged -= OnPositionChanged;
_geolocator.PositionChanged += OnPositionChanged;
_geolocator.StatusChanged -= Geolocal_StatusChangedAsync;
_geolocator.StatusChanged += Geolocal_StatusChangedAsync;
_geolocator.DesiredAccuracy = Windows.Devices.Geolocation.PositionAccuracy.Default;
//_geolocator.DesiredAccuracy = Windows.Devices.Geolocation.PositionAccuracy.High;
break;
case GeolocationAccessStatus.Denied:
//ResetLocationGraphic();
await NoLocationRoutine();
break;
case GeolocationAccessStatus.Unspecified:
//ResetLocationGraphic();
await NoLocationRoutine();
break;
}
}
public async void Geolocal_StatusChangedAsync(Geolocator sender, Windows.Devices.Geolocation.StatusChangedEventArgs args)
{
switch (args.Status)
{
case PositionStatus.Ready:
StopLocationRing();
break;
case PositionStatus.Initializing:
//await Task.Delay(500);
if (FilenameValues.Count != 0) //This will prevent pop-up with new field book
{
StartLocationRing();
}
break;
case PositionStatus.NoData:
//// Location platform could not obtain location data.
if (!_progressRingActive)
{
StartLocationRing();
ResetLocationGraphic();
}
//await Task.Delay(3000); //Let enough time to pass so GPS actually gets a proper fix
//await NoLocationFlightMode();
//try
//{
// await SetGPS();
//}
//catch (Exception)
//{
//}
break;
case PositionStatus.Disabled:
await Task.Delay(500);
// The permission to access location data is denied by the user or other policies.
ResetLocationGraphic();
userHasTurnedGPSOff = true;
SetGPSModeIcon(Symbol.TouchPointer);
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
await NoLocationRoutine();
StopLocationRing();
}).AsTask();
//StopLocationRing();
break;
case PositionStatus.NotInitialized:
StartLocationRing();
await Task.Delay(500);
// The location platform is not initialized. This indicates that the application
//// has not made a request for location data.
//Clear current graphics
//ResetLocationGraphic();
try
{
await SetGPS();
}
catch (Exception)
{
}
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
ContentDialog notInitLocationDialog = new ContentDialog()
{
Title = local.GetString("MapPageDialogLocationTitle"),
Content = local.GetString("MapPageDialogLocationDidNotInit"),
CloseButtonText = local.GetString("GenericDialog_ButtonOK")
};
notInitLocationDialog.Style = (Style)Application.Current.Resources["WarningDialog"];
await Services.ContentDialogMaker.CreateContentDialogAsync(notInitLocationDialog, true);
StopLocationRing();
}).AsTask();
break;
case PositionStatus.NotAvailable:
await Task.Delay(500);
//// The location platform is not available on this version of the OS.
//Clear current graphics
ResetLocationGraphic();
userHasTurnedGPSOff = true;
SetGPSModeIcon(Symbol.TouchPointer);
try
{
await SetGPS();
}
catch (Exception)
{
throw;
}
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
ContentDialog NALocationDialog = new ContentDialog()
{
Title = local.GetString("MapPageDialogLocationTitle"),
Content = local.GetString("MapPageDialogLocationNAOnOS"),
CloseButtonText = local.GetString("GenericDialog_ButtonOK")
};
NALocationDialog.Style = (Style)Application.Current.Resources["WarningDialog"];
await Services.ContentDialogMaker.CreateContentDialogAsync(NALocationDialog, true);
StopLocationRing();
}).AsTask();
break;
default:
await Task.Delay(500);
ResetLocationGraphic();
userHasTurnedGPSOff = true;
SetGPSModeIcon(Symbol.TouchPointer);
try
{
await SetGPS();
}
catch (Exception)
{
throw;
}
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
ContentDialog defaultEventLocationDialog = new ContentDialog()
{
Title = local.GetString("MapPageDialogLocationTitle"),
Content = local.GetString("MapPageDialogLocationUnknownError"),
CloseButtonText = local.GetString("GenericDialog_ButtonOK")
};
defaultEventLocationDialog.Style = (Style)Application.Current.Resources["WarningDialog"];
await Services.ContentDialogMaker.CreateContentDialogAsync(defaultEventLocationDialog, true);
StopLocationRing();
}).AsTask();
break;
}
}
/// <summary>
/// Will make a quick verification whether user has still the right to get a location
/// </summary>
/// <returns></returns>
public async Task<bool> ValidateGeolocationAccess()
{
var accessStatus = await Geolocator.RequestAccessAsync();
bool canAccess = true;
switch (accessStatus)
{
case GeolocationAccessStatus.Allowed:
currentMapView.Tapped -= myMapView_AddByTap;
canAccess = true;
break;
case GeolocationAccessStatus.Denied:
canAccess = false;
//Force call on UI thread, else it could crash the app if async call is made another thread.
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
ContentDialog tapModeDialog = new ContentDialog()
{
Title = local.GetString("MapPageDialogLocationTitle"),
Content = local.GetString("MapPageDialogLocationRestricted"),
CloseButtonText = local.GetString("GenericDialog_ButtonOK")
};
tapModeDialog.Style = (Style)Application.Current.Resources["WarningDialog"];
await Services.ContentDialogMaker.CreateContentDialogAsync(tapModeDialog, true);
}).AsTask();
break;
case GeolocationAccessStatus.Unspecified:
canAccess = false;
//Force call on UI thread, else it could crash the app if async call is made another thread.
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
ContentDialog tapModeDialog = new ContentDialog()
{
Title = local.GetString("MapPageDialogLocationTitle"),
Content = local.GetString("MapPageDialogLocationRestricted"),
CloseButtonText = local.GetString("GenericDialog_ButtonOK")
};
tapModeDialog.Style = (Style)Application.Current.Resources["WarningDialog"];
await Services.ContentDialogMaker.CreateContentDialogAsync(tapModeDialog, true);
}).AsTask();
break;
}
return canAccess;
}
/// <summary>
/// Will display database stations and display them on the map
/// </summary>
/// <param name="inMapView"></param>
/// <param name="inLocationTableRows"></param>
public void DisplayPointAndLabelsAsync(MapView inMapView, bool forceRefresh = false)
{
#region Load from Default Database
//Build a list of already loaded stations id on the map
Dictionary<string, Graphic> loadedGraphicList = new Dictionary<string, Graphic>();
if (forceRefresh)
{
foreach (Graphic gr in _OverlayStation.Graphics)
{
loadedGraphicList[gr.Attributes[Dictionaries.DatabaseLiterals.FieldLocationID].ToString()] = gr;
}
}
// If at least one location exists display it on the map
if (!forceRefresh && inMapView != null)
{
//Reset main db station overlay
inMapView.GraphicsOverlays.Remove(_OverlayStation);
inMapView.GraphicsOverlays.Remove(_OverlayStationLabel);
inMapView.GraphicsOverlays.Remove(_OverlayStructure);
inMapView.GraphicsOverlays.Add(_OverlayStation);
inMapView.GraphicsOverlays.Add(_OverlayStationLabel);
inMapView.GraphicsOverlays.Add(_OverlayStructure);
// Load
LoadFromGivenDBTest(loadedGraphicList, true);
//inMapView.UpdateLayout();
}
else
{
//Refresh graphics since the last location seems to have been deleted by the user
if (currentMapView != null && currentMapView.GraphicsOverlays != null && currentMapView.GraphicsOverlays.Count > 0)
{
_OverlayStation.Graphics.Clear();
_OverlayStationLabel.Graphics.Clear();
_OverlayStructure.Graphics.Clear();
currentMapView.GraphicsOverlays.Remove(_OverlayStation);
currentMapView.GraphicsOverlays.Remove(_OverlayStationLabel);
currentMapView.GraphicsOverlays.Remove(_OverlayStructure);
RaisePropertyChanged("_OverlayStation");
RaisePropertyChanged("_OverlayStationLabel");
RaisePropertyChanged("_OverlayStructure");
}
}
#endregion
}
/// <summary>
/// From a given database connection , will add point and labels of stations on the map page
/// Information will be loaded if the schema is the same between all databases and the version with which
/// this application version has been coded.
/// </summary>
/// <param name="inLocationTableRows"></param>
public void LoadFromGivenDB(List<object> inLocationTableRows, SQLiteConnection dbConnection, Dictionary<string, Graphic> graphicList, bool isDefaultDB)
{
//PictureMarkerSymbol pointSym = new PictureMarkerSymbol(new Uri("ms-appx:///Assets/IC809393.png"));
//Uri planarPath = new Uri("ms-appx:///Assets/Images/theme-light/struc_planar.png");
//Uri linearPath = new Uri("ms-appx:///Assets/Images/theme-light/struc_linear.png");
//PictureMarkerSymbol StrucPlaneSym = new PictureMarkerSymbol(planarPath);
//PictureMarkerSymbol StrucLinearSym = new PictureMarkerSymbol(linearPath);
////Choose proper overlay
//GraphicsOverlay pointOverlay = new GraphicsOverlay();
//GraphicsOverlay pointLabelOverlay = new GraphicsOverlay();
//GraphicsOverlay structureOverlay = new GraphicsOverlay();
////Set some rendering defaults
//Renderer graphRenderer = new SimpleRenderer
//{
// RotationType = RotationType.Geographic
//};
//pointOverlay.Renderer = graphRenderer;
//if (isDefaultDB)
//{
// pointOverlay = _OverlayStation;
// pointLabelOverlay = _OverlayStationLabel;
// structureOverlay = _OverlayStructure;
//}
//else
//{
// string dbFileName = Path.GetFileName(dbConnection.DatabasePath);
// if (_overlayContainerOther.ContainsKey(dbFileName))
// {
// pointOverlay = _overlayContainerOther[dbFileName][0];
// pointLabelOverlay = _overlayContainerOther[dbFileName][1];
// structureOverlay = _overlayContainerOther[dbFileName][2];
// }
//}
//#region ADD
//// Get latitude, longitude and station id and add to graphics overlay
//foreach (object lcs in inLocationTableRows)
//{
// //Variables
// bool stationGraphicExists = false;
// bool structureGraphicExists = false;
// #region POINT SYMBOL
// Models.FieldLocation currentLocation = lcs as Models.FieldLocation;
// var ptLatitude = currentLocation.LocationLat;
// var ptLongitude = currentLocation.LocationLong;
// var ptLocId = currentLocation.LocationID;
// //Get related station
// List<object> stationTableRows = new List<object>();
// Station stations = new Station();
// string stationsSelectionQuery = "Select * from " + DatabaseLiterals.TableStation + " where " + DatabaseLiterals.FieldLocationID + " = '" + currentLocation.LocationID + "'";
// stationTableRows = accessData.ReadTableFromDBConnectionWithoutClosingConnection(stations.GetType(), stationsSelectionQuery, dbConnection);
// // should only be one station returned, this approach doesn't allow for multiple stations
// var ptStationId = string.Empty;
// var ptStationDate = string.Empty;
// var ptStationTime = string.Empty;
// var ptStationType = string.Empty;
// string ptStationLocationID = string.Empty;
// double ptStationLocationLat;
// double ptStationLocationLong;
// string ptStationLocationEPSG = string.Empty;
// foreach (object scs in stationTableRows)
// {
// Models.Station currentStation = scs as Models.Station;
// ptStationId = currentStation.StationAlias;
// ptStationDate = currentStation.StationVisitDate;
// ptStationTime = currentStation.StationVisitTime;
// ptStationType = currentStation.StationObsType;
// ptStationLocationID = currentLocation.LocationID;
// ptStationLocationLat = currentLocation.LocationLat;
// ptStationLocationLong = currentLocation.LocationLong;
// ptStationLocationEPSG = currentLocation.LocationDatum;
// }
// //Find if station was already loaded
// if (graphicList.ContainsKey(currentLocation.LocationID))
// {
// stationGraphicExists = true;
// graphicList.Remove(currentLocation.LocationID);
// }
// //Add new graphic station and it's related label if needed
// if (!stationGraphicExists && ptStationId != null && ptStationId != string.Empty)
// {
// //Tracking available offset placement
// List<int> placementPool = Enumerable.Range(1, 8).ToList();
// #region MAIN POINT
// //Create Map Point for graphic
// MapPoint geoPoint = new MapPoint(ptLongitude, ptLatitude, SpatialReferences.Wgs84);
// //Get if datum transformation is needed
// int.TryParse(ptStationLocationEPSG, out int epsg);
// if (epsg != 0 && epsg != 4326)
// {
// DatumTransformation datumTransfo = null;
// SpatialReference outSR = null;
// if ((epsg > 26900 && epsg < 27000))
// {
// outSR = SpatialReference.Create(4326);
// datumTransfo = TransformationCatalog.GetTransformation(outSR, SpatialReferences.Wgs84);
// }
// MapPoint proPoint = new MapPoint(ptLongitude, ptLatitude, outSR);
// //Validate if transformation is needed.
// if (datumTransfo != null)
// {
// //Replace geopoint
// geoPoint = (MapPoint)Esri.ArcGISRuntime.Geometry.GeometryEngine.Project(proPoint, SpatialReferences.Wgs84, datumTransfo);
// }
// }
// var StationGraphic = new Graphic(geoPoint, pointSym);
// StationGraphic.Attributes.Add("Id", ptStationId.ToString());
// StationGraphic.Attributes.Add("Date", ptStationDate.ToString());
// StationGraphic.Attributes.Add("Time", ptStationTime.ToString());
// StationGraphic.Attributes.Add("tableType", DatabaseLiterals.TableStation);
// StationGraphic.Attributes.Add(Dictionaries.DatabaseLiterals.FieldLocationID, ptStationLocationID.ToString());
// if (ptStationType != null)
// {
// StationGraphic.Attributes.Add("Type", ptStationType.ToString());
// }
// else
// {
// StationGraphic.Attributes.Add("Type", string.Empty);
// }
// StationGraphic.Attributes.Add("Default", isDefaultDB);
// pointOverlay.Graphics.Add(StationGraphic);
// #endregion
// #region LABEL SYMBOL
// GraphicPlacement placements = new GraphicPlacement();
// var textSym = new TextSymbol
// {
// FontFamily = "Arial",
// FontWeight = FontWeight.Bold,
// Color = System.Drawing.Color.Black,
// HaloColor = System.Drawing.Color.WhiteSmoke,
// HaloWidth = 2,
// Size = 16,
// HorizontalAlignment = Esri.ArcGISRuntime.Symbology.HorizontalAlignment.Left,
// VerticalAlignment = Esri.ArcGISRuntime.Symbology.VerticalAlignment.Baseline,
// OffsetX = placements.GetOffsetFromPlacementPriority(placementPool[0]).Item1,
// OffsetY = placements.GetOffsetFromPlacementPriority(placementPool[0]).Item2
// };
// placementPool.RemoveAt(0); //Remove taken placement from pool
// textSym.Text = ptStationId.ToString();
// pointLabelOverlay.Graphics.Add(new Graphic(new MapPoint(ptLongitude, ptLatitude, SpatialReferences.Wgs84), textSym));
// #endregion
// #region STRUCTURES
// ///For structure symboles (planar and linear) make sure they are wanted by user but that it's within a bedrock field notebook also
// if ((bool)localSettings.GetSettingValue(ApplicationLiterals.KeyworkStructureSymbols) && _mapPageQuickMeasurementEnable)
// {
// //Get related structures, if any
// List<object> strucTableRows = new List<object>();
// Structure structs = new Structure();
// string structSelectionQuery = "SELECT s.* FROM " + DatabaseLiterals.TableStructure + " s" +
// " JOIN " + DatabaseLiterals.TableEarthMat + " e on e." + DatabaseLiterals.FieldStructureParentID + " = s." + DatabaseLiterals.FieldEarthMatID +
// " JOIN " + DatabaseLiterals.TableStation + " st on st." + DatabaseLiterals.FieldStationID + " = e." + DatabaseLiterals.FieldEarthMatStatID +
// " WHERE st." + DatabaseLiterals.FieldStationAlias + " = '" + ptStationId + "';";
// strucTableRows = accessData.ReadTableFromDBConnectionWithoutClosingConnection(structs.GetType(), structSelectionQuery, dbConnection);
// //Variables
// if (!structureGraphicExists && strucTableRows.Count() > 0)
// {
// //Structure pairs tracking
// //Key = record ID, Value = priority number for placement
// Dictionary<string, int> strucPairs = new Dictionary<string, int>();
// int iteration = 1;
// foreach (Structure sts in strucTableRows)
// {
// //Manage pair tracking for pool placement
// if (!strucPairs.ContainsKey(sts.StructureID))
// {
// if (sts.StructureRelated != null && sts.StructureRelated != String.Empty)
// {
// //Get related struc placement priority
// strucPairs[sts.StructureID] = strucPairs[sts.StructureRelated];
// }
// else
// {
// //Assign new priority and remove it from the pool
// strucPairs[sts.StructureID] = iteration;
// iteration = iteration + 1;
// }
// }
// //Set proper symbol
// PictureMarkerSymbol strucSym = StrucPlaneSym.Clone() as PictureMarkerSymbol;
// if (sts.StructureClass == DatabaseLiterals.KeywordLinear)
// {
// strucSym = StrucLinearSym.Clone() as PictureMarkerSymbol;
// }
// //Set azim
// double.TryParse(sts.StructureSymAng, out double azimAngle);
// if (azimAngle != 0.0)
// {
// strucSym.Angle = azimAngle;
// }
// strucSym.AngleAlignment = SymbolAngleAlignment.Map; //Set to map else symbol will keep same direction or mapview is rotated
// //Set offset
// Tuple<double, double> symOffset = placements.GetPositionOffsetFromPlacementPriority(strucPairs[sts.StructureID], ptLongitude, ptLatitude, 100.0);
// //Create Map Point for graphic
// MapPoint geoStructPoint = new MapPoint(symOffset.Item1, symOffset.Item2, SpatialReferences.Wgs84);
// //Get if datum transformation is needed
// if (epsg != 0 && epsg != 4326)
// {
// DatumTransformation datumTransfo = null;
// SpatialReference outSR = null;
// if ((epsg > 26900 && epsg < 27000))
// {
// outSR = SpatialReference.Create(4617);
// datumTransfo = TransformationCatalog.GetTransformation(outSR, SpatialReferences.Wgs84);
// }
// MapPoint proPoint = new MapPoint(ptLongitude, ptLatitude, outSR);
// //Validate if transformation is needed.
// if (datumTransfo != null)
// {
// //Replace geopoint
// geoStructPoint = (MapPoint)Esri.ArcGISRuntime.Geometry.GeometryEngine.Project(proPoint, SpatialReferences.Wgs84, datumTransfo);
// }
// }
// //TODO make up for a different way to measure azim (not right hand rule)
// var Sgraphic = new Graphic(geoStructPoint, strucSym);
// Sgraphic.Attributes.Add("Id", sts.StructureName.ToString());
// Sgraphic.Attributes.Add("Date", ptStationDate.ToString());
// Sgraphic.Attributes.Add("ParentID", sts.StructureParentID);
// Sgraphic.Attributes.Add("StructureClass", sts.getClassTypeDetail);
// Sgraphic.Attributes.Add("Azim", sts.StructureAzimuth.ToString());
// Sgraphic.Attributes.Add("Dip", sts.StructureDipPlunge.ToString());
// Sgraphic.Attributes.Add("Default", isDefaultDB);
// Sgraphic.Attributes.Add("tableType", DatabaseLiterals.TableStructure);
// Sgraphic.Attributes.Add(Dictionaries.DatabaseLiterals.FieldLocationID, ptStationLocationID.ToString());
// structureOverlay.Graphics.Add(Sgraphic);
// //Set station symbol to transparent so we clearly see the structures instead
// //StationGraphic.IsVisible = false;
// }
// }
// else
// {
// }
// }
// else
// {
// //Set station symbol to transparent so we clearly see the structures instead
// StationGraphic.IsVisible = true;
// structureOverlay.Graphics.Clear();
// }
// #endregion
// }
// #endregion
//}
//#endregion
//#region REMOVE
////For remaining loc in loadedGraphicList
//foreach (KeyValuePair<string, Graphic> grr in graphicList)
//{
// int indexOfGraphic = pointOverlay.Graphics.IndexOf(grr.Value);
// pointOverlay.Graphics.RemoveAt(indexOfGraphic);
// pointLabelOverlay.Graphics.RemoveAt(indexOfGraphic);
//}
//#endregion
}
/// <summary>
/// From a given database connection , will add point and labels of stations on the map page
/// Information will be loaded if the schema is the same between all databases and the version with which
/// this application version has been coded.
/// </summary>
/// <param name="inLocationTableRows"></param>
public void LoadFromGivenDBTest(Dictionary<string, Graphic> graphicList, bool isDefaultDB)
{
PictureMarkerSymbol pointSym = new PictureMarkerSymbol(new Uri("ms-appx:///Assets/IC809393.png"));
Uri planarPath = new Uri("ms-appx:///Assets/Images/theme-light/struc_planar.png");
Uri linearPath = new Uri("ms-appx:///Assets/Images/theme-light/struc_linear.png");
PictureMarkerSymbol StrucPlaneSym = new PictureMarkerSymbol(planarPath);
PictureMarkerSymbol StrucLinearSym = new PictureMarkerSymbol(linearPath);
//Choose proper overlay
GraphicsOverlay pointOverlay = new GraphicsOverlay();
GraphicsOverlay pointLabelOverlay = new GraphicsOverlay();
GraphicsOverlay structureOverlay = new GraphicsOverlay();
//Set some rendering defaults
Renderer graphRenderer = new SimpleRenderer
{
RotationType = RotationType.Geographic
};
pointOverlay.Renderer = graphRenderer;
if (isDefaultDB)
{
pointOverlay = _OverlayStation;
pointLabelOverlay = _OverlayStationLabel;
structureOverlay = _OverlayStructure;
}
#region ADD
string selectMetadata = "SELECT * FROM " + DatabaseLiterals.TableMetadata + " fm ";
string joinLocation = "JOIN " + DatabaseLiterals.TableLocation + " fl on fm." + DatabaseLiterals.FieldUserInfoID + " = fl." + DatabaseLiterals.FieldLocationMetaID + " ";
string joinStation = "JOIN " + DatabaseLiterals.TableStation + " fs on fl." + DatabaseLiterals.FieldLocationID + " = fs." + DatabaseLiterals.FieldStationObsID + " ";
string whereMetadata = string.Empty;
if (localSetting.GetSettingValue(Dictionaries.DatabaseLiterals.FieldUserInfoID) != null)
{
whereMetadata = " WHERE fm." + DatabaseLiterals.FieldUserInfoID + " = '" + localSetting.GetSettingValue(Dictionaries.DatabaseLiterals.FieldUserInfoID).ToString() + "'";
}
MapPageStation mps = new MapPageStation();
List<object> mpsRows = new List<object>();
mpsRows = accessData.ReadTable(mps.GetType(), selectMetadata + joinLocation + joinStation + whereMetadata);
// Get latitude, longitude and station id and add to graphics overlay
foreach (object m in mpsRows)
{
//Variables
bool stationGraphicExists = false;
bool structureGraphicExists = false;
#region POINT SYMBOL
// should only be one station returned, this approach doesn't allow for multiple stations
MapPageStation currentStationLocation = m as MapPageStation;
var ptStationId = currentStationLocation.StationID;
var ptStationAlias = currentStationLocation.StationAlias;
var ptStationDate = currentStationLocation.StationVisitDate;
var ptStationTime = currentStationLocation.StationVisitTime;
var ptStationType = currentStationLocation.StationObsType;
var ptStationLocationID = currentStationLocation.LocationID;
var ptStationLocationLat = currentStationLocation.LocationLat;
var ptStationLocationLong = currentStationLocation.LocationLong;
var ptStationLocationEPSG = currentStationLocation.LocationDatum;