-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMapControl.cs
1057 lines (845 loc) · 34 KB
/
MapControl.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;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Net;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using Mapsui;
using Mapsui.Fetcher;
using Mapsui.Layers;
using Mapsui.Logging;
using Mapsui.Providers;
using Mapsui.Rendering.Skia;
using Mapsui.UI;
using Mapsui.UI.Utils;
using Mapsui.UI.Wpf;
using Mapsui.Utilities;
using Mapsui.Rendering;
using Mapsui.Widgets;
using SkiaSharp.Views.Desktop;
using SkiaSharp.Views.WPF;
using HorizontalAlignment = System.Windows.HorizontalAlignment;
using Point = System.Windows.Point;
using VerticalAlignment = System.Windows.VerticalAlignment;
using XamlVector = System.Windows.Vector;
namespace TacControl.Misc
{
public enum RenderMode
{
Skia,
Wpf
}
public interface ISkiaCanvas
{
[Category("Appearance")]
event EventHandler<SKPaintSurfaceEventArgs> PaintSurface;
[Category("Appearance")]
event EventHandler<SKPaintGLSurfaceEventArgs> PaintSurfaceGL;
Visibility Visibility{ get; set; }
void InvalidateVisual();
}
public partial class MapControl : Grid, IMapControl
{
//https://github.com/Mapsui/Mapsui/blob/af2bf64d3f45c0a3a7b91d2d58cc2a4fff3d13d3/Mapsui.UI.Shared/MapControl.cs
private Map _map;
private double _unSnapRotationDegrees;
/// <summary>
/// After how many degrees start rotation to take place
/// </summary>
public double UnSnapRotationDegrees
{
get { return _unSnapRotationDegrees; }
set
{
if (_unSnapRotationDegrees != value)
{
_unSnapRotationDegrees = value;
OnPropertyChanged();
}
}
}
private double _reSnapRotationDegrees;
/// <summary>
/// With how many degrees from 0 should map snap to 0 degrees
/// </summary>
public double ReSnapRotationDegrees
{
get { return _reSnapRotationDegrees; }
set
{
if (_reSnapRotationDegrees != value)
{
_reSnapRotationDegrees = value;
OnPropertyChanged();
}
}
}
public float PixelDensity
{
get => GetPixelDensity();
}
private IRenderer _renderer = new MapRenderer();
/// <summary>
/// Renderer that is used from this MapControl
/// </summary>
public IRenderer Renderer
{
get { return _renderer; }
set
{
if (_renderer != value)
{
_renderer = value;
OnPropertyChanged();
}
}
}
private readonly LimitedViewport _viewport = new LimitedViewport();
private INavigator _navigator;
/// <summary>
/// Viewport holding information about visible part of the map. Viewport can never be null.
/// </summary>
public IReadOnlyViewport Viewport => _viewport;
/// <summary>
/// Handles all manipulations of the map viewport
/// </summary>
public INavigator Navigator
{
get => _navigator;
set
{
if (_navigator != null)
{
_navigator.Navigated -= Navigated;
}
_navigator = value ?? throw new ArgumentException($"{nameof(Navigator)} can not be null");
_navigator.Navigated += Navigated;
}
}
private void Navigated(object sender, ChangeType changeType)
{
_map.Initialized = true;
Refresh(changeType);
}
/// <summary>
/// Called when the viewport is initialized
/// </summary>
public event EventHandler ViewportInitialized; //todo: Consider to use the Viewport PropertyChanged
/// <summary>
/// Called whenever a feature in one of the layers in InfoLayers is hitten by a click
/// </summary>
public event EventHandler<MapInfoEventArgs> Info;
/// <summary>
/// Called whenever a property is changed
/// </summary>
#if __FORMS__
public new event PropertyChangedEventHandler PropertyChanged;
protected override void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#else
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endif
/// <summary>
/// Unsubscribe from map events
/// </summary>
public void Unsubscribe()
{
UnsubscribeFromMapEvents(_map);
}
/// <summary>
/// Subscribe to map events
/// </summary>
/// <param name="map">Map, to which events to subscribe</param>
private void SubscribeToMapEvents(Map map)
{
map.DataChanged += MapDataChanged;
map.PropertyChanged += MapPropertyChanged;
}
/// <summary>
/// Unsubcribe from map events
/// </summary>
/// <param name="map">Map, to which events to unsubscribe</param>
private void UnsubscribeFromMapEvents(Map map)
{
var temp = map;
if (temp != null)
{
temp.DataChanged -= MapDataChanged;
temp.PropertyChanged -= MapPropertyChanged;
temp.AbortFetch();
}
}
/// <summary>
/// Refresh data of the map and than repaint it
/// </summary>
public void Refresh(ChangeType changeType = ChangeType.Discrete)
{
RefreshData(changeType);
RefreshGraphics();
}
private void MapDataChanged(object sender, DataChangedEventArgs e)
{
RunOnUIThread(() =>
{
try
{
if (e == null)
{
Logger.Log(LogLevel.Warning, "Unexpected error: DataChangedEventArgs can not be null");
}
else if (e.Cancelled)
{
Logger.Log(LogLevel.Warning, "Fetching data was cancelled", e.Error);
}
else if (e.Error is WebException)
{
Logger.Log(LogLevel.Warning, "A WebException occurred. Do you have internet?", e.Error);
}
else if (e.Error != null)
{
Logger.Log(LogLevel.Warning, "An error occurred while fetching data", e.Error);
}
else // no problems
{
RefreshGraphics();
}
}
catch (Exception exception)
{
Logger.Log(LogLevel.Warning, $"Unexpected exception in {nameof(MapDataChanged)}", exception);
}
});
}
// ReSharper disable RedundantNameQualifier - needed for iOS for disambiguation
private void MapPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(Mapsui.Layers.Layer.Enabled))
{
RefreshGraphics();
}
else if (e.PropertyName == nameof(Mapsui.Layers.Layer.Opacity))
{
RefreshGraphics();
}
else if (e.PropertyName == nameof(Map.BackColor))
{
RefreshGraphics();
}
else if (e.PropertyName == nameof(Mapsui.Layers.Layer.DataSource))
{
Refresh(); // There is a new DataSource so let's fetch the new data.
}
else if (e.PropertyName == nameof(Map.Envelope))
{
CallHomeIfNeeded();
Refresh();
}
else if (e.PropertyName == nameof(Map.Layers))
{
CallHomeIfNeeded();
Refresh();
}
if (e.PropertyName.Equals(nameof(Map.Limiter)))
{
_viewport.Limiter = Map.Limiter;
}
}
// ReSharper restore RedundantNameQualifier
public void CallHomeIfNeeded()
{
if (_map != null && !_map.Initialized && _viewport.HasSize && _map?.Envelope != null)
{
_map.Home?.Invoke(Navigator);
_map.Initialized = true;
}
}
/// <summary>
/// Map holding data for which is shown in this MapControl
/// </summary>
public Map Map
{
get => _map;
set
{
if (_map != null)
{
UnsubscribeFromMapEvents(_map);
_map = null;
}
_map = value;
if (_map != null)
{
SubscribeToMapEvents(_map);
Navigator = new Navigator(_map, _viewport);
_viewport.Map = Map;
_viewport.Limiter = Map.Limiter;
CallHomeIfNeeded();
}
Refresh();
OnPropertyChanged();
}
}
/// <inheritdoc />
public Mapsui.Geometries.Point ToPixels(Mapsui.Geometries.Point coordinateInDeviceIndependentUnits)
{
return new Mapsui.Geometries.Point(
coordinateInDeviceIndependentUnits.X * PixelDensity,
coordinateInDeviceIndependentUnits.Y * PixelDensity);
}
/// <inheritdoc />
public Mapsui.Geometries.Point ToDeviceIndependentUnits(Mapsui.Geometries.Point coordinateInPixels)
{
return new Mapsui.Geometries.Point(coordinateInPixels.X / PixelDensity, coordinateInPixels.Y / PixelDensity);
}
private void OnViewportSizeInitialized()
{
ViewportInitialized?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Refresh data of Map, but don't paint it
/// </summary>
public void RefreshData(ChangeType changeType = ChangeType.Discrete)
{
_map?.RefreshData(Viewport.Extent, Viewport.Resolution, changeType);
}
private void OnInfo(MapInfoEventArgs mapInfoEventArgs)
{
if (mapInfoEventArgs == null) return;
Info?.Invoke(this, mapInfoEventArgs);
}
private bool WidgetTouched(IWidget widget, Mapsui.Geometries.Point screenPosition)
{
var result = widget.HandleWidgetTouched(Navigator, screenPosition);
if (!result && widget is Hyperlink hyperlink && !string.IsNullOrWhiteSpace(hyperlink.Url))
{
OpenBrowser(hyperlink.Url);
return true;
}
return false;
}
/// <inheritdoc />
public MapInfo GetMapInfo(Mapsui.Geometries.Point screenPosition, int margin = 0)
{
return Renderer.GetMapInfo(screenPosition.X, screenPosition.Y, Viewport, Map.Layers, margin);
}
/// <inheritdoc />
public byte[] GetSnapshot(IEnumerable<ILayer> layers = null)
{
byte[] result = null;
using (var stream = Renderer.RenderToBitmapStream(Viewport, layers ?? Map.Layers, pixelDensity: PixelDensity))
{
if (stream != null)
result = stream.ToArray();
}
return result;
}
/// <summary>
/// Check if a widget or feature at a given screen position is clicked/tapped
/// </summary>
/// <param name="screenPosition">Screen position to check for widgets and features</param>
/// <param name="startScreenPosition">Screen position of Viewport/MapControl</param>
/// <param name="numTaps">Number of clickes/taps</param>
/// <returns>True, if something done </returns>
private MapInfoEventArgs InvokeInfo(Mapsui.Geometries.Point screenPosition, Mapsui.Geometries.Point startScreenPosition, int numTaps)
{
return InvokeInfo(
Map.GetWidgetsOfMapAndLayers(),
screenPosition,
startScreenPosition,
WidgetTouched,
numTaps);
}
/// <summary>
/// Check if a widget or feature at a given screen position is clicked/tapped
/// </summary>
/// <param name="widgets">The Map widgets</param>
/// <param name="screenPosition">Screen position to check for widgets and features</param>
/// <param name="startScreenPosition">Screen position of Viewport/MapControl</param>
/// <param name="widgetCallback">Callback, which is called when Widget is hit</param>
/// <param name="numTaps">Number of clickes/taps</param>
/// <returns>True, if something done </returns>
private MapInfoEventArgs InvokeInfo(IEnumerable<IWidget> widgets, Mapsui.Geometries.Point screenPosition,
Mapsui.Geometries.Point startScreenPosition, Func<IWidget, Mapsui.Geometries.Point, bool> widgetCallback, int numTaps)
{
// Check if a Widget is tapped. In the current design they are always on top of the map.
var touchedWidgets = WidgetTouch.GetTouchedWidget(screenPosition, startScreenPosition, widgets);
foreach (var widget in touchedWidgets)
{
var result = widgetCallback(widget, screenPosition);
if (result)
{
return new MapInfoEventArgs
{
Handled = true
};
}
}
// Check which features in the map were tapped.
var mapInfo = Renderer.GetMapInfo(screenPosition.X, screenPosition.Y, Viewport, Map.Layers);
if (mapInfo != null)
{
return new MapInfoEventArgs
{
MapInfo = mapInfo,
NumTaps = numTaps,
Handled = false
};
}
return null;
}
private void SetViewportSize()
{
var hadSize = Viewport.HasSize;
_viewport.SetSize(ViewportWidth, ViewportHeight);
if (!hadSize && Viewport.HasSize) OnViewportSizeInitialized();
CallHomeIfNeeded();
Refresh();
}
/// <summary>
/// Clear cache and repaint map
/// </summary>
public void Clear()
{
// not sure if we need this method
_map?.ClearCache();
RefreshGraphics();
}
// https://github.com/Mapsui/Mapsui/blob/af2bf64d3f45c0a3a7b91d2d58cc2a4fff3d13d3/Mapsui.UI.Wpf/MapControl.cs
private readonly Rectangle _selectRectangle = CreateSelectRectangle();
private Mapsui.Geometries.Point _currentMousePosition;
private Mapsui.Geometries.Point _downMousePosition;
private bool _mouseDown;
private Mapsui.Geometries.Point _previousMousePosition;
private RenderMode _renderMode;
private bool _hasBeenManipulated;
private double _innerRotation;
private readonly FlingTracker _flingTracker = new FlingTracker();
public MouseWheelAnimation MouseWheelAnimation { get; } = new MouseWheelAnimation();
/// <summary>
/// Fling is called, when user release mouse button or lift finger while moving with a certain speed, higher than speed of swipe
/// </summary>
public event EventHandler<SwipedEventArgs> Fling;
static private bool GLRunning = false; // true == GL rendering completely disabled, false == one GL window allowed
public MapControl()
{
Children.Add(WpfCanvas);
if (!GLRunning)
{
SkiaCanvas = CreateSkiaGLRenderElement();
GLRunning = true;
Children.Add(SkiaCanvas as SKGLWpfControl);
}
else
{
SkiaCanvas = CreateSkiaRenderElement();
Children.Add(SkiaCanvas as SKElement);
}
SkiaCanvas.PaintSurfaceGL += SKGLElementOnPaintSurface;
SkiaCanvas.PaintSurface += SKElementOnPaintSurface;
Children.Add(_selectRectangle);
Map = new Map();
Loaded += MapControlLoaded;
MouseRightButtonDown += MapControlMouseLeftButtonDown;
MouseRightButtonUp += MapControlMouseLeftButtonUp;
TouchUp += MapControlTouchUp;
MouseMove += MapControlMouseMove;
MouseLeave += MapControlMouseLeave;
MouseWheel += MapControlMouseWheel;
SizeChanged += MapControlSizeChanged;
ManipulationStarted += OnManipulationStarted;
ManipulationDelta += OnManipulationDelta;
ManipulationCompleted += OnManipulationCompleted;
ManipulationInertiaStarting += OnManipulationInertiaStarting;
IsManipulationEnabled = true;
RenderMode = RenderMode.Skia;
}
protected override void OnRender(DrawingContext dc)
{
if (RenderMode == RenderMode.Wpf) PaintWpf();
base.OnRender(dc);
}
private static Rectangle CreateSelectRectangle()
{
return new Rectangle
{
Fill = new SolidColorBrush(Colors.Red),
Stroke = new SolidColorBrush(Colors.Black),
StrokeThickness = 3,
RadiusX = 0.5,
RadiusY = 0.5,
StrokeDashArray = new DoubleCollection { 3.0 },
Opacity = 0.3,
VerticalAlignment = VerticalAlignment.Top,
HorizontalAlignment = HorizontalAlignment.Left,
Visibility = Visibility.Collapsed
};
}
public Canvas WpfCanvas { get; } = CreateWpfRenderCanvas();
private ISkiaCanvas SkiaCanvas { get; }
public RenderMode RenderMode
{
get => _renderMode;
set
{
_renderMode = value;
if (_renderMode == RenderMode.Skia)
{
WpfCanvas.Visibility = Visibility.Collapsed;
SkiaCanvas.Visibility = Visibility.Visible;
Renderer = new MapRenderer();
RefreshGraphics();
}
else
{
SkiaCanvas.Visibility = Visibility.Collapsed;
WpfCanvas.Visibility = Visibility.Visible;
Renderer = new Mapsui.Rendering.Xaml.MapRenderer();
RefreshGraphics();
}
OnPropertyChanged();
}
}
private static Canvas CreateWpfRenderCanvas()
{
return new Canvas
{
VerticalAlignment = VerticalAlignment.Stretch,
HorizontalAlignment = HorizontalAlignment.Stretch
};
}
private static int mVersion = 0;
private static SKGLWpfControl CreateSkiaGLRenderElement()
{
return new SKGLWpfControl(mVersion++);
}
private static SKElement CreateSkiaRenderElement()
{
return new SKElement
{
VerticalAlignment = VerticalAlignment.Stretch,
HorizontalAlignment = HorizontalAlignment.Stretch
};
}
public event EventHandler<FeatureInfoEventArgs> FeatureInfo; // todo: Remove and add sample for alternative
public void RefreshGraphics()
{
if (Dispatcher.CheckAccess()) InvalidateCanvas();
else RunOnUIThread(InvalidateCanvas);
}
internal void InvalidateCanvas()
{
if (RenderMode == RenderMode.Wpf) InvalidateVisual(); // To trigger OnRender of this MapControl
else SkiaCanvas.InvalidateVisual();
}
private void MapControlLoaded(object sender, RoutedEventArgs e)
{
SetViewportSize();
Focusable = true;
}
private void MapControlMouseWheel(object sender, MouseWheelEventArgs e)
{
if (Map.ZoomLock) return;
if (!Viewport.HasSize) return;
_currentMousePosition = e.GetPosition(this).ToMapsui();
var resolution = MouseWheelAnimation.GetResolution(e.Delta, _viewport, _map);
// Limit target resolution before animation to avoid an animation that is stuck on the max resolution, which would cause a needless delay
resolution = Map.Limiter.LimitResolution(resolution, Viewport.Width, Viewport.Height, Map.Resolutions, Map.Envelope);
Navigator.ZoomTo(resolution, _currentMousePosition, MouseWheelAnimation.Duration, MouseWheelAnimation.Easing);
}
private void MapControlSizeChanged(object sender, SizeChangedEventArgs e)
{
Clip = new RectangleGeometry { Rect = new Rect(0, 0, ActualWidth, ActualHeight) };
SetViewportSize();
}
private void MapControlMouseLeave(object sender, MouseEventArgs e)
{
_previousMousePosition = new Mapsui.Geometries.Point();
ReleaseMouseCapture();
}
private void RunOnUIThread(Action action)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.BeginInvoke(action);
}
else
{
action();
}
}
private void MapControlMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// We have a new interaction with the screen, so stop all navigator animations
Navigator.StopRunningAnimation();
var touchPosition = e.GetPosition(this).ToMapsui();
_previousMousePosition = touchPosition;
_downMousePosition = touchPosition;
_mouseDown = true;
_flingTracker.Clear();
CaptureMouse();
if (!IsInBoxZoomMode())
{
if (IsClick(_currentMousePosition, _downMousePosition))
{
HandleFeatureInfo(e);
var mapInfoEventArgs = InvokeInfo(touchPosition, _downMousePosition, e.ClickCount);
OnInfo(mapInfoEventArgs);
}
}
}
private static bool IsInBoxZoomMode()
{
return Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl);
}
private void MapControlMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var mousePosition = e.GetPosition(this).ToMapsui();
if (IsInBoxZoomMode())
{
var previous = Viewport.ScreenToWorld(_previousMousePosition.X, _previousMousePosition.Y);
var current = Viewport.ScreenToWorld(mousePosition.X, mousePosition.Y);
ZoomToBox(previous, current);
}
RefreshData();
_mouseDown = false;
double velocityX;
double velocityY;
(velocityX, velocityY) = _flingTracker.CalcVelocity(1, DateTime.Now.Ticks);
if (Math.Abs(velocityX) > 200 || Math.Abs(velocityY) > 200)
{
// This was the last finger on screen, so this is a fling
e.Handled = OnFlinged(velocityX, velocityY);
}
_flingTracker.RemoveId(1);
_previousMousePosition = new Mapsui.Geometries.Point();
ReleaseMouseCapture();
}
/// <summary>
/// Called, when mouse/finger/pen flinged over map
/// </summary>
/// <param name="velocityX">Velocity in x direction in pixel/second</param>
/// <param name="velocityY">Velocity in y direction in pixel/second</param>
private bool OnFlinged(double velocityX, double velocityY)
{
var args = new SwipedEventArgs(velocityX, velocityY);
Fling?.Invoke(this, args);
if (args.Handled)
return true;
Navigator.FlingWith(velocityX, velocityY, 1000);
return true;
}
private static bool IsClick(Mapsui.Geometries.Point currentPosition, Mapsui.Geometries.Point previousPosition)
{
return
Math.Abs(currentPosition.X - previousPosition.X) < SystemParameters.MinimumHorizontalDragDistance &&
Math.Abs(currentPosition.Y - previousPosition.Y) < SystemParameters.MinimumVerticalDragDistance;
}
private void MapControlTouchUp(object sender, TouchEventArgs e)
{
if (!_hasBeenManipulated)
{
var touchPosition = e.GetTouchPoint(this).Position.ToMapsui();
// todo: Pass the touchDown position. It needs to be set at touch down.
// todo: Figure out how to do a number of taps for WPF
OnInfo(InvokeInfo(touchPosition, touchPosition, 1));
}
}
public void OpenBrowser(string url)
{
Process.Start(url);
}
private void HandleFeatureInfo(MouseButtonEventArgs e)
{
if (FeatureInfo == null) return; // don't fetch if you the call back is not set.
if (_downMousePosition == e.GetPosition(this).ToMapsui())
foreach (var layer in Map.Layers)
{
// ReSharper disable once SuspiciousTypeConversion.Global
(layer as IFeatureInfo)?.GetFeatureInfo(Viewport, _downMousePosition.X, _downMousePosition.Y,
OnFeatureInfo);
}
}
private void OnFeatureInfo(IDictionary<string, IEnumerable<IFeature>> features)
{
FeatureInfo?.Invoke(this, new FeatureInfoEventArgs { FeatureInfo = features });
}
private void MapControlMouseMove(object sender, MouseEventArgs e)
{
if (IsInBoxZoomMode())
{
DrawBbox(e.GetPosition(this));
return;
}
_currentMousePosition = e.GetPosition(this).ToMapsui(); //Needed for both MouseMove and MouseWheel event
if (_mouseDown)
{
if (_previousMousePosition == null || _previousMousePosition.IsEmpty())
{
// Usually MapControlMouseLeftButton down initializes _previousMousePosition but in some
// situations it can be null. So far I could only reproduce this in debug mode when putting
// a breakpoint and continuing.
return;
}
_flingTracker.AddEvent(1, _currentMousePosition, DateTime.Now.Ticks);
_viewport.Transform(_currentMousePosition, _previousMousePosition);
RefreshGraphics();
_previousMousePosition = _currentMousePosition;
}
else
{
if (MouseWheelAnimation.IsAnimating())
{
// Disabled because not performing:
// Navigator.ZoomTo(_toResolution, _currentMousePosition, _mouseWheelAnimationDuration, Easing.QuarticOut);
}
}
}
public void ZoomToBox(Mapsui.Geometries.Point beginPoint, Mapsui.Geometries.Point endPoint)
{
var width = Math.Abs(endPoint.X - beginPoint.X);
var height = Math.Abs(endPoint.Y - beginPoint.Y);
if (width <= 0) return;
if (height <= 0) return;
ZoomHelper.ZoomToBoudingbox(beginPoint.X, beginPoint.Y, endPoint.X, endPoint.Y,
ActualWidth, ActualHeight, out var x, out var y, out var resolution);
Navigator.NavigateTo(new Mapsui.Geometries.Point(x, y), resolution, 384);
RefreshData();
RefreshGraphics();
ClearBBoxDrawing();
}
private void ClearBBoxDrawing()
{
RunOnUIThread(() => _selectRectangle.Visibility = Visibility.Collapsed);
}
private void DrawBbox(Point newPos)
{
if (_mouseDown)
{
var from = _previousMousePosition;
var to = newPos;
if (from.X > to.X)
{
var temp = from;
from.X = to.X;
to.X = temp.X;
}
if (from.Y > to.Y)
{
var temp = from;
from.Y = to.Y;
to.Y = temp.Y;
}
_selectRectangle.Width = to.X - from.X;
_selectRectangle.Height = to.Y - from.Y;
_selectRectangle.Margin = new Thickness(from.X, from.Y, 0, 0);
_selectRectangle.Visibility = Visibility.Visible;
}
}
private float ViewportWidth => (float)ActualWidth;
private float ViewportHeight => (float)ActualHeight;
private static void OnManipulationInertiaStarting(object sender, ManipulationInertiaStartingEventArgs e)
{
e.TranslationBehavior.DesiredDeceleration = 25 * 96.0 / (1000.0 * 1000.0);
}
private void OnManipulationStarted(object sender, ManipulationStartedEventArgs e)
{
_hasBeenManipulated = false;
_innerRotation = _viewport.Rotation;
}
private void OnManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
var translation = e.DeltaManipulation.Translation;
var center = e.ManipulationOrigin.ToMapsui().Offset(translation.X, translation.Y);
var radius = GetDeltaScale(e.DeltaManipulation.Scale);
var angle = e.DeltaManipulation.Rotation;
var previousCenter = e.ManipulationOrigin.ToMapsui();
var previousRadius = 1f;
var prevAngle = 0f;
_hasBeenManipulated |= Math.Abs(e.DeltaManipulation.Translation.X) > SystemParameters.MinimumHorizontalDragDistance
|| Math.Abs(e.DeltaManipulation.Translation.Y) > SystemParameters.MinimumVerticalDragDistance;
double rotationDelta = 0;
if (!Map.RotationLock)
{
_innerRotation += angle - prevAngle;
_innerRotation %= 360;
if (_innerRotation > 180)
_innerRotation -= 360;
else if (_innerRotation < -180)
_innerRotation += 360;
if (Viewport.Rotation == 0 && Math.Abs(_innerRotation) >= Math.Abs(UnSnapRotationDegrees))
rotationDelta = _innerRotation;
else if (Viewport.Rotation != 0)
{
if (Math.Abs(_innerRotation) <= Math.Abs(ReSnapRotationDegrees))
rotationDelta = -Viewport.Rotation;
else
rotationDelta = _innerRotation - Viewport.Rotation;
}
}
_viewport.Transform(center, previousCenter, radius / previousRadius, rotationDelta);
RefreshGraphics();
e.Handled = true;
}
private double GetDeltaScale(XamlVector scale)
{
if (Map.ZoomLock) return 1;
var deltaScale = (scale.X + scale.Y) / 2;
if (Math.Abs(deltaScale) < Constants.Epsilon)
return 1; // If there is no scaling the deltaScale will be 0.0 in Windows Phone (while it is 1.0 in wpf)
if (!(Math.Abs(deltaScale - 1d) > Constants.Epsilon)) return 1;
return deltaScale;
}
private void OnManipulationCompleted(object sender, ManipulationCompletedEventArgs e)