This repository has been archived by the owner on Sep 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathMapView.cs
1832 lines (1608 loc) · 47.7 KB
/
MapView.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
// OsmSharp - OpenStreetMap (OSM) SDK
// Copyright (C) 2013 Abelshausen Ben
//
// This file is part of OsmSharp.
//
// OsmSharp is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// OsmSharp is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with OsmSharp. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Threading;
using OsmSharp.Logging;
using OsmSharp.Math.Geo;
using OsmSharp.Math.Geo.Projections;
using OsmSharp.Math.Primitives;
using OsmSharp.UI;
using OsmSharp.UI.Animations;
using OsmSharp.UI.Animations.Invalidation.Triggers;
using OsmSharp.UI.Map;
using OsmSharp.UI.Map.Layers;
using OsmSharp.UI.Renderer;
using OsmSharp.UI.Renderer.Primitives;
using OsmSharp.UI.Renderer.Scene;
using OsmSharp.Units.Angle;
using System.Collections.ObjectModel;
using OsmSharp.iOS.UI.Controls;
#if __UNIFIED__
using CoreAnimation;
using CoreGraphics;
using Foundation;
using UIKit;
#else
using MonoTouch.UIKit;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.CoreGraphics;
using MonoTouch.CoreAnimation;
// Type Mappings Unified to monotouch.dll
using CGRect = global::System.Drawing.RectangleF;
using CGSize = global::System.Drawing.SizeF;
using CGPoint = global::System.Drawing.PointF;
using nfloat = global::System.Single;
using nint = global::System.Int32;
using nuint = global::System.UInt32;
#endif
namespace OsmSharp.iOS.UI
{
/// <summary>
/// Map view.
/// </summary>
[Register("MapView")]
public class MapView : UIView, IMapView, IInvalidatableMapSurface, IMapControlHost
{
private const float MAX_ZOOM_LEVEL = 22;
private bool _invertX = false;
private bool _invertY = false;
/// <summary>
/// Map touched down event.
/// </summary>
public event MapViewDelegates.MapTouchedDelegate MapTouchedDown;
/// <summary>
/// Map touched event.
/// </summary>
public event MapViewDelegates.MapTouchedDelegate MapTouched;
/// <summary>
/// Map touched up event.
/// </summary>
public event MapViewDelegates.MapTouchedDelegate MapTouchedUp;
/// <summary>
/// Raised when the map was first initialized, meaning it has a size and it was rendered for the first time.
/// </summary>
public event MapViewDelegates.MapInitialized MapInitialized;
/// <summary>
/// Raised when the map moves.
/// </summary>
public event MapViewDelegates.MapMoveDelegate MapMove;
/// <summary>
/// Initializes a new instance of the <see cref="OsmSharp.iOS.UI.MapView"/> class.
/// </summary>
/// <param name="handle">Handle.</param>
public MapView(IntPtr handle) : base(handle)
{
this.Initialize(new GeoCoordinate(0, 0), new Map(), 0, 16);
}
/// <summary>
/// Initializes a new instance of the <see cref="OsmSharp.iOS.UI.MapView"/> class.
/// </summary>
/// <param name="t">T.</param>
public MapView(NSObjectFlag t) : base(t)
{
this.Initialize(new GeoCoordinate(0, 0), new Map(), 0, 16);
}
/// <summary>
/// Initializes a new instance of the <see cref="OsmSharp.iOS.UI.MapView"/> class.
/// </summary>
/// <param name="coder">Coder.</param>
public MapView(NSCoder coder) : base(coder)
{
this.Initialize(new GeoCoordinate(0, 0), new Map(), 0, 16);
}
/// <summary>
/// Initializes a new instance of the <see cref="OsmSharp.iOS.UI.MapView"/> class.
/// </summary>
/// <param name="frame">Frame.</param>
public MapView(CGRect frame) : base(frame)
{
this.Initialize(new GeoCoordinate(0, 0), new Map(), 0, 16);
}
/// <summary>
/// Initializes a new instance of the <see cref="OsmSharp.iOS.UI.MapView"/> class.
/// </summary>
public MapView()
{
this.Initialize(new GeoCoordinate(0, 0), new Map(), 0, 16);
}
/// <summary>
/// Initializes a new instance of the <see cref="OsmSharp.iOS.UI.MapView"/> class.
/// </summary>
/// <param name="mapCenter">Map center.</param>
/// <param name="map">Map.</param>
/// <param name="defaultZoom">Default zoom.</param>
public MapView(GeoCoordinate mapCenter, Map map, float defaultZoom)
{
this.Initialize(mapCenter, map, 0, defaultZoom);
}
/// <summary>
/// Initializes a new instance of the <see cref="OsmSharp.iOS.UI.MapView"/> class.
/// </summary>
/// <param name="mapCenter">Map center.</param>
/// <param name="map">Map.</param>
/// <param name="mapTilt">Map tilt.</param>
/// <param name="defaultZoom">Default zoom.</param>
public MapView(GeoCoordinate mapCenter, Map map, Degree mapTilt, float defaultZoom)
{
this.Initialize(mapCenter, map, mapTilt, defaultZoom);
}
/// <summary>
/// Initialize the specified defaultMapCenter, defaultMap, defaultMapTilt and defaultMapZoom.
/// </summary>
/// <param name="defaultMapCenter">Default map center.</param>
/// <param name="defaultMap">Default map.</param>
/// <param name="defaultMapTilt">Default map tilt.</param>
/// <param name="defaultMapZoom">Default map zoom.</param>
public void Initialize(GeoCoordinate defaultMapCenter, Map defaultMap, Degree defaultMapTilt, float defaultMapZoom)
{
// register the default listener.
(this as IInvalidatableMapSurface).RegisterListener(new DefaultTrigger(this));
_displayLink = CADisplayLink.Create (OnPreRender);
_displayLink.AddToRunLoop (NSRunLoop.Current, NSRunLoopMode.Default);
// enable all interactions by default.
this.MapAllowPan = true;
this.MapAllowTilt = true;
this.MapAllowZoom = true;
// set clip to bounds to prevent objects from being rendered/show outside of the mapview.
this.ClipsToBounds = true;
MapCenter = defaultMapCenter;
_map = defaultMap;
MapTilt = defaultMapTilt;
MapZoom = defaultMapZoom;
_map.MapChanged += MapChanged;
_doubleTapAnimator = new MapViewAnimator(this);
this.BackgroundColor = UIColor.White;
this.UserInteractionEnabled = true;
if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0))
{
var panGesture = new UIPanGestureRecognizer(Pan);
panGesture.ShouldRecognizeSimultaneously += (UIGestureRecognizer r, UIGestureRecognizer other) =>
{
return true;
};
// TODO: workaround for xamarin bug, remove later!
panGesture.ShouldRequireFailureOf = (a, b) =>
{
return false;
};
panGesture.ShouldBeRequiredToFailBy = (a, b) =>
{
return false;
};
this.AddGestureRecognizer(panGesture);
var pinchGesture = new UIPinchGestureRecognizer(Pinch);
pinchGesture.ShouldRecognizeSimultaneously += (UIGestureRecognizer r, UIGestureRecognizer other) =>
{
return true;
};
// TODO: workaround for xamarin bug, remove later!
pinchGesture.ShouldRequireFailureOf = (a, b) =>
{
return false;
};
pinchGesture.ShouldBeRequiredToFailBy = (a, b) =>
{
return false;
};
this.AddGestureRecognizer(pinchGesture);
var rotationGesture = new UIRotationGestureRecognizer(Rotate);
rotationGesture.ShouldRecognizeSimultaneously += (UIGestureRecognizer r, UIGestureRecognizer other) =>
{
return true;
};
// TODO: workaround for xamarin bug, remove later!
rotationGesture.ShouldRequireFailureOf = (a, b) =>
{
return false;
};
rotationGesture.ShouldBeRequiredToFailBy = (a, b) =>
{
return false;
};
this.AddGestureRecognizer(rotationGesture);
var singleTapGesture = new UITapGestureRecognizer(SingleTap);
singleTapGesture.NumberOfTapsRequired = 1;
// TODO: workaround for xamarin bug, remove later!
// singleTapGesture.ShouldRequireFailureOf = (a, b) => { return false; };
// singleTapGesture.ShouldBeRequiredToFailBy = (a, b) => { return false; };
var doubleTapGesture = new UITapGestureRecognizer(DoubleTap);
doubleTapGesture.NumberOfTapsRequired = 2;
// TODO: workaround for xamarin bug, remove later!
// doubleTapGesture.ShouldRequireFailureOf = (a, b) => { return false; };
// doubleTapGesture.ShouldBeRequiredToFailBy = (a, b) => { return false; };
//singleTapGesture.RequireGestureRecognizerToFail (doubleTapGesture);
this.AddGestureRecognizer(singleTapGesture);
this.AddGestureRecognizer(doubleTapGesture);
}
else
{
var panGesture = new UIPanGestureRecognizer(Pan);
var pinchGesture = new UIPinchGestureRecognizer(Pinch);
var rotationGesture = new UIRotationGestureRecognizer(Rotate);
panGesture.ShouldRecognizeSimultaneously += (UIGestureRecognizer r, UIGestureRecognizer other) =>
{
return other != rotationGesture;
};
this.AddGestureRecognizer(panGesture);
pinchGesture.ShouldRecognizeSimultaneously += (UIGestureRecognizer r, UIGestureRecognizer other) =>
{
return true;
};
this.AddGestureRecognizer(pinchGesture);
rotationGesture.ShouldRecognizeSimultaneously += (UIGestureRecognizer r, UIGestureRecognizer other) =>
{
return true;
};
this.AddGestureRecognizer(rotationGesture);
var singleTapGesture = new UITapGestureRecognizer(SingleTap);
singleTapGesture.NumberOfTapsRequired = 1;
//singleTapGesture.ShouldRecognizeSimultaneously += ShouldRecognizeSimultaneouslySingle;
//singleTapGesture.ShouldBeRequiredToFailBy += ShouldRecognizeSimultaneouslySingle;
var doubleTapGesture = new UITapGestureRecognizer(DoubleTap);
doubleTapGesture.NumberOfTapsRequired = 2;
//doubleTapGesture.ShouldRecognizeSimultaneously += ShouldRecognizeSimultaneouslySingle;
//doubleTapGesture.ShouldBeRequiredToFailBy += ShouldRecognizeSimultaneouslyDouble;
singleTapGesture.RequireGestureRecognizerToFail(doubleTapGesture);
this.AddGestureRecognizer(singleTapGesture);
this.AddGestureRecognizer(doubleTapGesture);
}
// set scalefactor.
_scaleFactor = (float)this.ContentScaleFactor;
// create the cache renderer.
_cacheRenderer = new MapRenderer<CGContextWrapper>(
new CGContextRenderer(_scaleFactor));
_backgroundColor = SimpleColor.FromKnownColor(KnownColor.White).Value;
}
/// <summary>
/// Gets or sets the frame.
/// </summary>
/// <value>The frame.</value>
public override CGRect Frame
{
get
{
return base.Frame;
}
set
{
base.Frame = value;
if (_rect.Width == 0 && value.Width != 0)
{ // trigger the initial rendering when the frame has a size for the first time.
_rect = value;
(this as IMapView).Invalidate();
}
}
}
/// <summary>
/// Gestures the recognizer should begin.
/// </summary>
/// <returns><c>true</c>, if recognizer should begin was gestured, <c>false</c> otherwise.</returns>
/// <param name="gestureRecognizer">Gesture recognizer.</param>
public override bool GestureRecognizerShouldBegin(UIGestureRecognizer gestureRecognizer)
{
return true;
}
/// <summary>
/// Holds the cache renderer.
/// </summary>
private MapRenderer<CGContextWrapper> _cacheRenderer;
/// <summary>
/// The
/// </summary>
private CGRect _rect;
/// <summary>
/// Holds the on screen buffered image.
/// </summary>
private ImageTilted2D _onScreenBuffer;
/// <summary>
/// Holds the buffer synchronisation object.
/// </summary>
private object _bufferSynchronisation = new object();
/// <summary>
/// Holds the render synchronisation object.
/// </summary>
private object _renderSynchronisation = new object();
/// <summary>
/// Holds the background color.
/// </summary>
private int _backgroundColor;
/// <summary>
/// Holds the rendering loop thread.
/// </summary>
private Thread _renderingLoopThread;
/// <summary>
/// Do we need a new render?
/// </summary>
private bool _renderingIsDirty = false;
/// <summary>
/// Cancellation token for the most recently launched rendering loop.
/// </summary>
private CancellationTokenSource _renderingLoopCancellationTokenSource;
/// <summary>
/// A lock to engage when starting or stopping the rendering loop, which is therefore nonatomic.
/// </summary>
private readonly object _renderingLoopToggleLock = new object();
/// <summary>
/// If true, we need to notify movement at some point in the near future.
/// </summary>
private bool _notifyMovementWanted = false;
/// <summary>
/// This display link performs notification of movement if a trigger is wanted. This must be on the primary thread.
/// </summary>
private CADisplayLink _displayLink;
/// <summary>
/// Notifies change
/// </summary>
internal void TriggerRendering(bool force)
{
if (_rect.Width == 0)
{
return;
}
try
{
// create the view that would be use for rendering.
float size = (float)System.Math.Max(_rect.Width, _rect.Height);
View2D view = _cacheRenderer.Create((int)(size * _extra), (int)(size * _extra),
this.Map, (float)this.Map.Projection.ToZoomFactor(this.MapZoom),
this.MapCenter, _invertX, _invertY, this.MapTilt);
if(force || _previouslyRenderedView == null || !view.Equals(_previouslyRenderedView)) {
_renderingIsDirty = true;
StartRenderingLoopIfNecessary();
}
else {
_listener.NotifyRenderSuccess(view, this.MapZoom, 0);
}
_previouslyRenderedView = view;
OsmSharp.Logging.Log.TraceEvent("MapView.TriggerRendering", TraceEventType.Information,
"Rendering triggered.");
}
catch
{
OsmSharp.Logging.Log.TraceEvent("MapView.TriggerRendering", TraceEventType.Information,
"Exception Occured: Rendering not triggered.");
}
}
private void StartRenderingLoopIfNecessary() {
lock (_renderingLoopToggleLock) {
if (_renderingLoopThread == null) {
_renderingLoopCancellationTokenSource = new CancellationTokenSource ();
var token = _renderingLoopCancellationTokenSource.Token;
ThreadStart starter = () => RenderingLoop (token);
_renderingLoopThread = new Thread (starter);
_renderingLoopThread.Start ();
OsmSharp.Logging.Log.TraceEvent ("MapViewSurface", TraceEventType.Verbose, "Started rendering loop");
}
}
}
private void StopRenderingLoop() {
lock (_renderingLoopToggleLock) {
if (_renderingLoopCancellationTokenSource != null) {
_renderingLoopCancellationTokenSource.Cancel ();
_renderingLoopCancellationTokenSource = null;
_renderingLoopThread = null;
OsmSharp.Logging.Log.TraceEvent ("MapViewSurface", TraceEventType.Verbose, "Stopped rendering loop");
}
}
}
/// <summary>
/// Holds the scale factor.
/// </summary>
private float _scaleFactor = 1;
/// <summary>
/// Holds the extra border.
/// </summary>
private float _extra = 1.5f;
/// <summary>
/// Holds the previous rendered zoom.
/// </summary>
private View2D _previouslyRenderedView;
/// <summary>
/// Render the current complete scene.
/// </summary>
private void RenderingLoop(CancellationToken cancellationToken)
{
while (cancellationToken.IsCancellationRequested == false) {
var rect = _rect;
var surfaceSizeFailure = rect.Width == 0 || rect.Height == 0;
var cannotRender = surfaceSizeFailure;
var renderNow = _renderingIsDirty && !cannotRender;
if (!renderNow) {
const int standardSleepDuration = 20;
Thread.Sleep (standardSleepDuration);
} else {
_renderingIsDirty = false;
lock (_cacheRenderer) {
try {
// create the view.
var size = (float)System.Math.Max (_rect.Width, _rect.Height);
var view = _cacheRenderer.Create ((int)(size * _extra), (int)(size * _extra),
this.Map, (float)this.Map.Projection.ToZoomFactor (this.MapZoom),
this.MapCenter, _invertX, _invertY, this.MapTilt);
// calculate width/height.
var imageWidth = (int)(size * _extra * _scaleFactor);
var imageHeight = (int)(size * _extra * _scaleFactor);
// create a new bitmap context.
var space = CGColorSpace.CreateDeviceRGB ();
int bytesPerPixel = 4;
int bytesPerRow = bytesPerPixel * imageWidth;
int bitsPerComponent = 8;
// get old image if available.
var image = new CGBitmapContext (null, imageWidth, imageHeight,
bitsPerComponent, bytesPerRow,
space, // kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast
CGBitmapFlags.PremultipliedFirst | CGBitmapFlags.ByteOrder32Big);
long before = DateTime.Now.Ticks;
// build the layers list.
var layers = new List<Layer> ();
for (int layerIdx = 0; layerIdx < this.Map.LayerCount; layerIdx++) {
layers.Add (this.Map [layerIdx]);
}
image.SetFillColor (1, 1, 1, 1);
image.FillRect (new CGRect (
0, 0, imageWidth, imageHeight));
// notify the map that the view has changed.
var normalView = _cacheRenderer.Create ((float)_rect.Width, (float)_rect.Height,
this.Map, (float)this.Map.Projection.ToZoomFactor (this.MapZoom),
this.MapCenter, _invertX, _invertY, this.MapTilt);
this.Map.ViewChanged ((float)this.Map.Projection.ToZoomFactor (this.MapZoom), this.MapCenter,
normalView, view);
long afterViewChanged = DateTime.Now.Ticks;
OsmSharp.Logging.Log.TraceEvent ("OsmSharp.iOS.UI.MapView", TraceEventType.Information,
"View change took: {0}ms @ zoom level {1}",
(new TimeSpan (afterViewChanged - before).TotalMilliseconds), this.MapZoom);
float zoomFactor = this.MapZoom;
float sceneZoomFactor = (float)this.Map.Projection.ToZoomFactor (this.MapZoom);
// does the rendering.
bool complete = _cacheRenderer.Render (new CGContextWrapper (image,
new CGRect (0, 0, (int)(size * _extra), (int)(size * _extra))),
_map.Projection, layers, view, sceneZoomFactor);
long afterRendering = DateTime.Now.Ticks;
if (complete) { // there was no cancellation, the rendering completely finished.
lock (_bufferSynchronisation) {
if (_onScreenBuffer != null &&
_onScreenBuffer.NativeImage != null) { // on screen buffer.
_onScreenBuffer.NativeImage.Dispose ();
}
// add the newly rendered image again.
_onScreenBuffer = new ImageTilted2D (view.Rectangle,
new NativeImage (image.ToImage ()), float.MinValue, float.MaxValue);
// store the previous view.
_previouslyRenderedView = view;
}
// make sure this view knows that there is a new rendering.
this.InvokeOnMainThread (SetNeedsDisplay);
}
long after = DateTime.Now.Ticks;
if (complete) { // notify invalidation listener about a succesfull rendering.
OsmSharp.Logging.Log.TraceEvent ("OsmSharp.iOS.UI.MapView", TraceEventType.Information,
"Rendering succesfull after {0}ms.", new TimeSpan (after - before).TotalMilliseconds);
_listener.NotifyRenderSuccess (view, zoomFactor, (int)new TimeSpan (after - before).TotalMilliseconds);
} else { // rendering incomplete.
OsmSharp.Logging.Log.TraceEvent ("OsmSharp.iOS.UI.MapView", TraceEventType.Information,
"Rendering cancelled.", new TimeSpan (after - before).TotalMilliseconds);
}
} catch (Exception) {
_cacheRenderer.Reset ();
}
}
}
}
}
/// <summary>
/// Holds the map view before rotating.
/// </summary>
private View2D _mapViewBefore;
/// <summary>
/// Rotate the specified rotation.
/// </summary>
/// <param name="rotation">Rotation.</param>
private void Rotate(UIRotationGestureRecognizer rotation)
{
CGRect rect = this.Frame;
if (this.MapAllowTilt &&
rect.Width > 0 && this.Map != null)
{
this.StopCurrentAnimation();
if (rotation.State == UIGestureRecognizerState.Ended)
{
this.NotifyMovement();;
_mapViewBefore = null;
// raise map touched event.
this.RaiseMapTouched();
this.RaiseMapTouchedUp();
}
else if (rotation.State == UIGestureRecognizerState.Began)
{
this.RaiseMapTouchedDown();
_mapViewBefore = this.CreateView(rect);
}
else
{
//_mapViewBefore = this.CreateView (_rect);
View2D rotatedView = _mapViewBefore.RotateAroundCenter((Radian)(float)rotation.Rotation);
_mapTilt = (float)((Degree)rotatedView.Rectangle.Angle).Value;
PointF2D sceneCenter = rotatedView.Rectangle.Center;
this.MapCenter = this.Map.Projection.ToGeoCoordinates(
sceneCenter[0], sceneCenter[1]);
this.NotifyMovement();
}
}
}
/// <summary>
/// Holds the map zoom level before pinching.
/// </summary>
private float? _mapZoomLevelBefore;
/// <summary>
/// Pinch the specified pinch.
/// </summary>
/// <param name="pinch">Pinch.</param>
private void Pinch(UIPinchGestureRecognizer pinch)
{
CGRect rect = this.Frame;
if (this.MapAllowZoom &&
rect.Width > 0)
{
this.StopCurrentAnimation();
if (pinch.State == UIGestureRecognizerState.Ended)
{
this.NotifyMovement();
_mapZoomLevelBefore = null;
// raise map touched event.
this.RaiseMapTouched();
this.RaiseMapTouchedUp();
}
else if (pinch.State == UIGestureRecognizerState.Began)
{
this.RaiseMapTouchedDown();
_mapZoomLevelBefore = MapZoom;
}
else
{
MapZoom = _mapZoomLevelBefore.Value;
double zoomFactor = this.Map.Projection.ToZoomFactor(MapZoom);
zoomFactor = zoomFactor * pinch.Scale;
MapZoom = (float)this.Map.Projection.ToZoomLevel(zoomFactor);
this.NotifyMovement();
}
}
}
/// <summary>
/// Holds the previous pan offset.
/// </summary>
private CGPoint _prevOffset;
/// <summary>
/// Pan the specified some.
/// </summary>
/// <param name="some">Some.</param>
private void Pan(UIPanGestureRecognizer pan)
{
CGRect rect = this.Frame;
if (this.MapAllowPan &&
rect.Width > 0 && this.Map != null)
{
this.StopCurrentAnimation();
CGPoint offset = pan.TranslationInView(this);
if (pan.State == UIGestureRecognizerState.Ended)
{
this.NotifyMovement();
// raise map touched event.
this.RaiseMapTouched();
this.RaiseMapTouchedUp();
}
else if (pan.State == UIGestureRecognizerState.Began)
{
_prevOffset = new CGPoint(0, 0);
this.RaiseMapTouchedDown();
}
else if (pan.State == UIGestureRecognizerState.Changed)
{
View2D view = this.CreateView(rect);
double centerXPixels = rect.Width / 2.0f - (offset.X - _prevOffset.X);
double centerYPixels = rect.Height / 2.0f - (offset.Y - _prevOffset.Y);
_prevOffset = offset;
double[] sceneCenter = view.FromViewPort(rect.Width, rect.Height,
centerXPixels, centerYPixels);
this.MapCenter = this.Map.Projection.ToGeoCoordinates(
sceneCenter[0], sceneCenter[1]);
this.NotifyMovement();
}
}
}
public delegate void MapTapEventDelegate(GeoCoordinate geoCoordinate);
/// <summary>
/// Occurs when the map was tapped at a certain location.
/// </summary>
public event MapTapEventDelegate MapTapEvent;
/// <summary>
/// Called when the map was single tapped at a certain location.
/// </summary>
/// <param name="tap">Tap.</param>
private void SingleTap(UITapGestureRecognizer tap)
{
CGRect rect = this.Frame;
if (rect.Width > 0 && rect.Height > 0 && this.Map != null)
{
this.StopCurrentAnimation();
if (this.MapTapEvent != null)
{
View2D view = this.CreateView(rect);
CGPoint location = tap.LocationInView(this);
double[] sceneCoordinates = view.FromViewPort(rect.Width, rect.Height, location.X, location.Y);
this.MapTapEvent(this.Map.Projection.ToGeoCoordinates(sceneCoordinates[0], sceneCoordinates[1]));
}
// notify controls map was tapped.
this.NotifyMapTapToControls();
}
}
/// <summary>
/// The map view animator to zoom/pan on double tap.
/// </summary>
private MapViewAnimator _doubleTapAnimator;
/// <summary>
/// Occurs when the map was double tapped at a certain location.
/// </summary>
public event MapTapEventDelegate DoubleMapTapEvent;
/// <summary>
/// Called when the tap gesture recognizer detects a double tap.
/// </summary>
/// <param name="tap">Tap.</param>
private void DoubleTap(UITapGestureRecognizer tap)
{
CGRect rect = this.Frame;
if (this.MapAllowZoom &&
rect.Width > 0 && rect.Height > 0 && this.Map != null)
{
this.StopCurrentAnimation();
View2D view = this.CreateView(rect);
CGPoint location = tap.LocationInView(this);
double[] sceneCoordinates = view.FromViewPort(rect.Width, rect.Height, location.X, location.Y);
GeoCoordinate geoLocation = this.Map.Projection.ToGeoCoordinates(sceneCoordinates[0], sceneCoordinates[1]);
if (this.DoubleMapTapEvent != null)
{
this.DoubleMapTapEvent(geoLocation);
}
else
{ // minimum zoom.
// Clamp the zoom level between the configured maximum and minimum.
float tapRequestZoom = MapZoom + 0.5f;
_doubleTapAnimator.Start(geoLocation, tapRequestZoom, new TimeSpan(0, 0, 0, 0, 500));
}
// notify controls map was tapped.
this.NotifyMapTapToControls();
}
}
/// <summary>
/// Notifies that there was movement by invoking NotifyMovement on the main thread.
/// </summary>
private void NotifyMovement()
{
_notifyMovementWanted = true;
}
/// <summary>
/// This method is called on the main thread prior to the rendering of any frame.
/// </summary>
private void OnPreRender()
{
if (_notifyMovementWanted) {
_notifyMovementWanted = false;
// invalidate the map.
this.InvalidateMap();
// change the map markers.
CGRect rect = this.Frame;
if (rect.Width > 0 && rect.Height > 0 && this.Map != null)
{
// create the current view.
View2D view = this.CreateView(rect);
_listener.NotifyChange(view, this.MapZoom);
}
// raise map move event.
this.RaiseMapMove();
}
}
/// <summary>
/// Holds the current invalidation listener.
/// </summary>
private TriggerBase _listener;
/// <summary>
/// Returns true if the map view is sure that it is still moving.
/// </summary>
/// <returns><c>true</c>, if moving was stilled, <c>false</c> otherwise.</returns>
bool IInvalidatableMapSurface.StillMoving()
{
return _mapViewAnimator != null;
}
/// <summary>
/// Triggers rendering.
/// </summary>
void IInvalidatableMapSurface.Render()
{
this.TriggerRendering(false);
}
/// <summary>
/// Cancels the current rendering.
/// </summary>
/// <returns><c>true</c> if this instance cancel render; otherwise, <c>false</c>.</returns>
void IInvalidatableMapSurface.CancelRender()
{
OsmSharp.Logging.Log.TraceEvent ("MapViewSurface", TraceEventType.Warning, "Request to cancel render ignored");
}
/// <summary>
/// Registers the listener.
/// </summary>
/// <param name="listener">Listener.</param>
void IInvalidatableMapSurface.RegisterListener(TriggerBase listener)
{
_listener = listener;
}
/// <summary>
/// Resets the listener.
/// </summary>
void IInvalidatableMapSurface.ResetListener()
{
_listener = null;
}
/// <summary>
/// Holds the map.
/// </summary>
private Map _map;
/// <summary>
/// Gets or sets the map.
/// </summary>
/// <value>The map.</value>
public Map Map
{
get { return _map; }
set {
if (_map != null)
{
_map.MapChanged-=MapChanged;
}
_map = value;
if (_map != null)
{
_map.MapChanged+=MapChanged;
}
}
}
/// <summary>
/// Holds the map zoom.
/// </summary>
private float _mapZoom;
/// <summary>
/// Gets or sets the zoom level.
/// </summary>
/// <value>The zoom level.</value>
public float MapZoom
{
get { return _mapZoom; }
set {
if (value > _mapMaxZoomLevel)
{
_mapZoom = _mapMaxZoomLevel;
}
else if (value < _mapMinZoomLevel)
{
_mapZoom = _mapMinZoomLevel;
}
else
{
_mapZoom = value;
}
this.NotifyMovement();
}
}
/// <summary>
/// Gets or sets the map max zoom level.
/// </summary>
/// <value>The map max zoom level.</value>
private float _mapMaxZoomLevel = MAX_ZOOM_LEVEL;
public float MapMaxZoomLevel
{
get { return _mapMaxZoomLevel; }
set { _mapMaxZoomLevel = (value < MAX_ZOOM_LEVEL) ? value : MAX_ZOOM_LEVEL; }
}
/// <summary>
/// Gets or sets the map minimum zoom level.
/// </summary>
/// <value>The map minimum zoom level.</value>
private float _mapMinZoomLevel = 0;
public float MapMinZoomLevel
{
get { return _mapMinZoomLevel; }
set { _mapMinZoomLevel = (value > 0) ? value : 0; }
}
/// <summary>
/// Holds the map tilte angle.
/// </summary>
private Degree _mapTilt;
/// <summary>
/// Gets or sets the map tilt.
/// </summary>
/// <value>The map tilt.</value>
public Degree MapTilt
{
get
{
return _mapTilt;
}
set
{
_mapTilt = value;
this.NotifyMovement();
}
}
/// <summary>
/// The map center.
/// </summary>
private GeoCoordinate _mapCenter;
/// <summary>
/// Gets or sets the center.
/// </summary>
/// <value>The center.</value>
public GeoCoordinate MapCenter
{
get { return _mapCenter; }
set
{
if (this.CurrentWidth == 0 || this.MapBoundingBox == null)
{
_mapCenter = value;
}
else
{
if (_rect.Width > 0 && _rect.Height > 0 && this.Map != null)