This repository has been archived by the owner on Aug 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
MGLMapView.mm
3479 lines (2873 loc) · 124 KB
/
MGLMapView.mm
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
#import "MGLMapView.h"
#import "MGLMapView+IBAdditions.h"
#import <mbgl/platform/log.hpp>
#import <mbgl/platform/gl.hpp>
#import <GLKit/GLKit.h>
#import <OpenGLES/EAGL.h>
#include <mbgl/mbgl.hpp>
#include <mbgl/annotation/point_annotation.hpp>
#include <mbgl/annotation/shape_annotation.hpp>
#include <mbgl/sprite/sprite_image.hpp>
#include <mbgl/map/camera.hpp>
#include <mbgl/platform/platform.hpp>
#include <mbgl/platform/darwin/reachability.h>
#include <mbgl/storage/sqlite_cache.hpp>
#include <mbgl/storage/default_file_source.hpp>
#include <mbgl/storage/network_status.hpp>
#include <mbgl/util/geo.hpp>
#include <mbgl/util/math.hpp>
#include <mbgl/util/constants.hpp>
#include <mbgl/util/image.hpp>
#include <mbgl/util/std.hpp>
#include <mbgl/util/default_styles.hpp>
#import "Mapbox.h"
#import "NSBundle+MGLAdditions.h"
#import "NSString+MGLAdditions.h"
#import "NSProcessInfo+MGLAdditions.h"
#import "NSException+MGLAdditions.h"
#import "MGLUserLocationAnnotationView.h"
#import "MGLUserLocation_Private.h"
#import "MGLAccountManager_Private.h"
#import "MGLMapboxEvents.h"
#import "SMCalloutView.h"
#import <algorithm>
#import <cstdlib>
#import <unordered_set>
class MBGLView;
NSString *const MGLDefaultStyleMarkerSymbolName = @"default_marker";
NSString *const MGLMapboxSetupDocumentationURLDisplayString = @"mapbox.com/help/first-steps-ios-sdk";
const NSTimeInterval MGLAnimationDuration = 0.3;
const CGSize MGLAnnotationUpdateViewportOutset = {150, 150};
const CGFloat MGLMinimumZoom = 3;
const CGFloat MGLMinimumPitch = 0;
const CGFloat MGLMaximumPitch = 60;
const CLLocationDegrees MGLAngularFieldOfView = M_PI / 6.;
const std::string spritePrefix = "com.mapbox.sprites.";
const NSUInteger MGLTargetFrameInterval = 1; //Target FPS will be 60 divided by this value
NSString *const MGLAnnotationIDKey = @"MGLAnnotationIDKey";
NSString *const MGLAnnotationSymbolKey = @"MGLAnnotationSymbolKey";
NSString *const MGLAnnotationSpritePrefix = @"com.mapbox.sprites.";
mbgl::util::UnitBezier MGLUnitBezierForMediaTimingFunction(CAMediaTimingFunction *function)
{
if ( ! function)
{
function = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
}
float p1[2], p2[2];
[function getControlPointAtIndex:0 values:p1];
[function getControlPointAtIndex:1 values:p2];
return { p1[0], p1[1], p2[0], p2[1] };
}
#pragma mark - Private -
@interface MGLMapView () <UIGestureRecognizerDelegate,
GLKViewDelegate,
CLLocationManagerDelegate,
UIActionSheetDelegate,
SMCalloutViewDelegate>
@property (nonatomic) EAGLContext *context;
@property (nonatomic) GLKView *glView;
@property (nonatomic) UIImageView *glSnapshotView;
@property (nonatomic) NSOperationQueue *regionChangeDelegateQueue;
@property (nonatomic, readwrite) UIImageView *compassView;
@property (nonatomic, readwrite) UIImageView *logoView;
@property (nonatomic) NS_MUTABLE_ARRAY_OF(NSLayoutConstraint *) *logoViewConstraints;
@property (nonatomic, readwrite) UIButton *attributionButton;
@property (nonatomic) NS_MUTABLE_ARRAY_OF(NSLayoutConstraint *) *attributionButtonConstraints;
@property (nonatomic) UIActionSheet *attributionSheet;
@property (nonatomic) UIPanGestureRecognizer *pan;
@property (nonatomic) UIPinchGestureRecognizer *pinch;
@property (nonatomic) UIRotationGestureRecognizer *rotate;
@property (nonatomic) UILongPressGestureRecognizer *quickZoom;
@property (nonatomic) UIPanGestureRecognizer *twoFingerDrag;
@property (nonatomic) NSMapTable *annotationMetadataByAnnotation;
@property (nonatomic) NS_MUTABLE_DICTIONARY_OF(NSString *, MGLAnnotationImage *) *annotationImages;
@property (nonatomic) std::vector<uint32_t> annotationsNearbyLastTap;
@property (nonatomic, weak) id <MGLAnnotation> selectedAnnotation;
@property (nonatomic) SMCalloutView *selectedAnnotationCalloutView;
@property (nonatomic) MGLUserLocationAnnotationView *userLocationAnnotationView;
@property (nonatomic) CLLocationManager *locationManager;
@property (nonatomic) CGPoint centerPoint;
@property (nonatomic) CGFloat scale;
@property (nonatomic) CGFloat angle;
@property (nonatomic) CGFloat quickZoomStart;
@property (nonatomic, getter=isDormant) BOOL dormant;
@property (nonatomic, getter=isAnimatingGesture) BOOL animatingGesture;
@property (nonatomic, readonly, getter=isRotationAllowed) BOOL rotationAllowed;
@end
@implementation MGLMapView
{
mbgl::Map *_mbglMap;
MBGLView *_mbglView;
std::shared_ptr<mbgl::SQLiteCache> _mbglFileCache;
mbgl::DefaultFileSource *_mbglFileSource;
NS_MUTABLE_ARRAY_OF(NSURL *) *_bundledStyleURLs;
BOOL _isWaitingForRedundantReachableNotification;
BOOL _isTargetingInterfaceBuilder;
CLLocationDegrees _pendingLatitude;
CLLocationDegrees _pendingLongitude;
CADisplayLink *_displayLink;
BOOL _needsDisplayRefresh;
}
#pragma mark - Setup & Teardown -
@dynamic debugActive;
std::chrono::steady_clock::duration durationInSeconds(float duration)
{
return std::chrono::duration_cast<std::chrono::steady_clock::duration>(std::chrono::duration<float, std::chrono::seconds::period>(duration));
}
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
[self commonInit];
self.styleURL = nil;
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame styleURL:(nullable NSURL *)styleURL
{
if (self = [super initWithFrame:frame])
{
[self commonInit];
self.styleURL = styleURL;
}
return self;
}
- (instancetype)initWithCoder:(nonnull NSCoder *)decoder
{
if (self = [super initWithCoder:decoder])
{
[self commonInit];
self.styleURL = nil;
}
return self;
}
+ (NS_SET_OF(NSString *) *)keyPathsForValuesAffectingStyleURL
{
return [NSSet setWithObjects:@"styleURL__", nil];
}
- (nonnull NSURL *)styleURL
{
NSString *styleURLString = @(_mbglMap->getStyleURL().c_str()).mgl_stringOrNilIfEmpty;
NSAssert(styleURLString || _isTargetingInterfaceBuilder, @"Invalid style URL string %@", styleURLString);
return styleURLString ? [NSURL URLWithString:styleURLString] : nil;
}
- (void)setStyleURL:(nullable NSURL *)styleURL
{
if (_isTargetingInterfaceBuilder) return;
if ( ! styleURL)
{
styleURL = [MGLStyle streetsStyleURL];
}
if ( ! [styleURL scheme])
{
// Assume a relative path into the application bundle.
styleURL = [NSURL URLWithString:[@"asset://" stringByAppendingString:[styleURL absoluteString]]];
}
_mbglMap->setStyleURL([[styleURL absoluteString] UTF8String]);
}
- (void)commonInit
{
_isTargetingInterfaceBuilder = NSProcessInfo.processInfo.mgl_isInterfaceBuilderDesignablesAgent;
BOOL background = [UIApplication sharedApplication].applicationState == UIApplicationStateBackground;
if (!background)
{
[self createGLView];
}
self.accessibilityLabel = @"Map";
self.backgroundColor = [UIColor clearColor];
self.clipsToBounds = YES;
// setup mbgl view
const float scaleFactor = [UIScreen instancesRespondToSelector:@selector(nativeScale)] ? [[UIScreen mainScreen] nativeScale] : [[UIScreen mainScreen] scale];
_mbglView = new MBGLView(self, scaleFactor);
// setup mbgl cache & file source
NSString *fileCachePath = @"";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
if ([paths count] != 0) {
NSString *libraryDirectory = [paths objectAtIndex:0];
fileCachePath = [libraryDirectory stringByAppendingPathComponent:@"cache.db"];
}
_mbglFileCache = mbgl::SharedSQLiteCache::get([fileCachePath UTF8String]);
_mbglFileSource = new mbgl::DefaultFileSource(_mbglFileCache.get());
// setup mbgl map
_mbglMap = new mbgl::Map(*_mbglView, *_mbglFileSource, mbgl::MapMode::Continuous);
// setup refresh driver
_displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateFromDisplayLink)];
_displayLink.frameInterval = MGLTargetFrameInterval;
[_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
_needsDisplayRefresh = YES;
// start paused if in IB
if (_isTargetingInterfaceBuilder || background) {
self.dormant = YES;
_mbglMap->pause();
}
// Observe for changes to the global access token (and find out the current one).
[[MGLAccountManager sharedManager] addObserver:self
forKeyPath:@"accessToken"
options:(NSKeyValueObservingOptionInitial |
NSKeyValueObservingOptionNew)
context:NULL];
// Notify map object when network reachability status changes.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kMGLReachabilityChangedNotification
object:nil];
MGLReachability* reachability = [MGLReachability reachabilityForInternetConnection];
if ([reachability isReachable])
{
_isWaitingForRedundantReachableNotification = YES;
}
[reachability startNotifier];
// setup annotations
//
_annotationMetadataByAnnotation = [NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory valueOptions:NSMapTableStrongMemory];
_annotationImages = [NSMutableDictionary dictionary];
// setup logo bug
//
UIImage *logo = [[MGLMapView resourceImageNamed:@"mapbox.png"] imageWithAlignmentRectInsets:UIEdgeInsetsMake(1.5, 4, 3.5, 2)];
_logoView = [[UIImageView alloc] initWithImage:logo];
_logoView.accessibilityLabel = @"Mapbox logo";
_logoView.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:_logoView];
_logoViewConstraints = [NSMutableArray array];
// setup attribution
//
_attributionButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
_attributionButton.accessibilityLabel = @"Attribution info";
[_attributionButton addTarget:self action:@selector(showAttribution) forControlEvents:UIControlEventTouchUpInside];
_attributionButton.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:_attributionButton];
_attributionButtonConstraints = [NSMutableArray array];
// setup compass
//
_compassView = [[UIImageView alloc] initWithImage:[MGLMapView resourceImageNamed:@"Compass.png"]];
_compassView.accessibilityLabel = @"Compass";
_compassView.frame = CGRectMake(0, 0, _compassView.image.size.width, _compassView.image.size.height);
_compassView.alpha = 0;
UIView *container = [[UIView alloc] initWithFrame:CGRectZero];
[container addSubview:_compassView];
container.translatesAutoresizingMaskIntoConstraints = NO;
[container addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleCompassTapGesture:)]];
[self addSubview:container];
// setup interaction
//
_pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
_pan.delegate = self;
_pan.maximumNumberOfTouches = 1;
[self addGestureRecognizer:_pan];
_scrollEnabled = YES;
_pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchGesture:)];
_pinch.delegate = self;
[self addGestureRecognizer:_pinch];
_zoomEnabled = YES;
_rotate = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotateGesture:)];
_rotate.delegate = self;
[self addGestureRecognizer:_rotate];
_rotateEnabled = YES;
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTapGesture:)];
doubleTap.numberOfTapsRequired = 2;
[self addGestureRecognizer:doubleTap];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapGesture:)];
[singleTap requireGestureRecognizerToFail:doubleTap];
[self addGestureRecognizer:singleTap];
UITapGestureRecognizer *twoFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTwoFingerTapGesture:)];
twoFingerTap.numberOfTouchesRequired = 2;
[twoFingerTap requireGestureRecognizerToFail:_pinch];
[twoFingerTap requireGestureRecognizerToFail:_rotate];
[self addGestureRecognizer:twoFingerTap];
_twoFingerDrag = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleTwoFingerDragGesture:)];
_twoFingerDrag.minimumNumberOfTouches = 2;
_twoFingerDrag.maximumNumberOfTouches = 2;
_twoFingerDrag.delegate = self;
[_twoFingerDrag requireGestureRecognizerToFail:twoFingerTap];
[_twoFingerDrag requireGestureRecognizerToFail:_pan];
[self addGestureRecognizer:_twoFingerDrag];
_pitchEnabled = YES;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
{
_quickZoom = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleQuickZoomGesture:)];
_quickZoom.numberOfTapsRequired = 1;
_quickZoom.minimumPressDuration = 0;
[_quickZoom requireGestureRecognizerToFail:doubleTap];
[self addGestureRecognizer:_quickZoom];
}
// observe app activity
//
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willTerminate) name:UIApplicationWillTerminateNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sleepGL:) name:UIApplicationDidEnterBackgroundNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wakeGL:) name:UIApplicationWillEnterForegroundNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wakeGL:) name:UIApplicationDidBecomeActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
// set initial position
//
mbgl::CameraOptions options;
options.center = mbgl::LatLng(0, 0);
options.zoom = _mbglMap->getMinZoom();
_mbglMap->jumpTo(options);
_pendingLatitude = NAN;
_pendingLongitude = NAN;
// setup change delegate queue
//
_regionChangeDelegateQueue = [NSOperationQueue new];
_regionChangeDelegateQueue.maxConcurrentOperationCount = 1;
// metrics: map load event
mbgl::LatLng latLng = _mbglMap->getLatLng();
int zoom = round(_mbglMap->getZoom());
[MGLMapboxEvents pushEvent:MGLEventTypeMapLoad withAttributes:@{
MGLEventKeyLatitude: @(latLng.latitude),
MGLEventKeyLongitude: @(latLng.longitude),
MGLEventKeyZoomLevel: @(zoom),
MGLEventKeyPushEnabled: @([MGLMapboxEvents checkPushEnabled])
}];
}
- (void)createGLView
{
if (_context) return;
// create context
//
_context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
NSAssert(_context, @"Failed to create OpenGL ES context.");
// create GL view
//
_glView = [[GLKView alloc] initWithFrame:self.bounds context:_context];
_glView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
_glView.enableSetNeedsDisplay = NO;
_glView.drawableStencilFormat = GLKViewDrawableStencilFormat8;
_glView.drawableDepthFormat = GLKViewDrawableDepthFormat16;
_glView.contentScaleFactor = [UIScreen instancesRespondToSelector:@selector(nativeScale)] ? [[UIScreen mainScreen] nativeScale] : [[UIScreen mainScreen] scale];
_glView.delegate = self;
[_glView bindDrawable];
[self insertSubview:_glView atIndex:0];
_glView.contentMode = UIViewContentModeCenter;
// load extensions
//
mbgl::gl::InitializeExtensions([](const char * name) {
static CFBundleRef framework = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.opengles"));
if (!framework) {
throw std::runtime_error("Failed to load OpenGL framework.");
}
CFStringRef str = CFStringCreateWithCString(kCFAllocatorDefault, name, kCFStringEncodingASCII);
void* symbol = CFBundleGetFunctionPointerForName(framework, str);
CFRelease(str);
return reinterpret_cast<mbgl::gl::glProc>(symbol);
});
}
- (void)reachabilityChanged:(NSNotification *)notification
{
MGLReachability *reachability = [notification object];
if ( ! _isWaitingForRedundantReachableNotification && [reachability isReachable])
{
mbgl::NetworkStatus::Reachable();
}
_isWaitingForRedundantReachableNotification = NO;
}
- (void)dealloc
{
[_regionChangeDelegateQueue cancelAllOperations];
[[NSNotificationCenter defaultCenter] removeObserver:self];
[[MGLAccountManager sharedManager] removeObserver:self forKeyPath:@"accessToken"];
if (_mbglMap)
{
delete _mbglMap;
_mbglMap = nullptr;
}
if (_mbglFileSource)
{
delete _mbglFileSource;
_mbglFileSource = nullptr;
}
if (_mbglView)
{
delete _mbglView;
_mbglView = nullptr;
}
if ([[EAGLContext currentContext] isEqual:_context])
{
[EAGLContext setCurrentContext:nil];
}
[self.logoViewConstraints removeAllObjects];
self.logoViewConstraints = nil;
[self.attributionButtonConstraints removeAllObjects];
self.attributionButtonConstraints = nil;
}
- (void)setDelegate:(nullable id<MGLMapViewDelegate>)delegate
{
if (_delegate == delegate) return;
_delegate = delegate;
if ([delegate respondsToSelector:@selector(mapView:symbolNameForAnnotation:)])
{
[NSException raise:@"Method unavailable" format:
@"-mapView:symbolNameForAnnotation: has been removed from the MGLMapViewDelegate protocol, but %@ still implements it. "
@"Implement -[%@ mapView:imageForAnnotation:] instead.",
NSStringFromClass([delegate class]), NSStringFromClass([delegate class])];
}
}
#pragma mark - Layout -
- (void)setFrame:(CGRect)frame
{
[super setFrame:frame];
[self setNeedsLayout];
}
- (void)setBounds:(CGRect)bounds
{
[super setBounds:bounds];
[self setNeedsLayout];
}
+ (BOOL)requiresConstraintBasedLayout
{
return YES;
}
- (UIViewController *)viewControllerForLayoutGuides
{
// Per -[UIResponder nextResponder] documentation, a UIView’s next responder
// is its managing UIViewController if applicable, or otherwise its
// superview. UIWindow’s next responder is UIApplication, which has no next
// responder.
UIResponder *laterResponder = self;
while ([laterResponder isKindOfClass:[UIView class]])
{
laterResponder = laterResponder.nextResponder;
}
if ([laterResponder isKindOfClass:[UIViewController class]])
{
return (UIViewController *)laterResponder;
}
return nil;
}
- (void)updateConstraints
{
// If we have a view controller reference, use its layout guides for our various top & bottom
// views so they don't underlap navigation or tool bars. If we don't have a reference, apply
// constraints against ourself to maintain (albeit less ideal) placement of the subviews.
//
UIViewController *viewController = self.viewControllerForLayoutGuides;
UIView *constraintParentView = (viewController.view ? viewController.view : self);
// compass
//
UIView *compassContainer = self.compassView.superview;
[compassContainer removeConstraints:compassContainer.constraints];
NSMutableArray *compassContainerConstraints = [NSMutableArray array];
if (viewController)
{
[compassContainerConstraints addObject:
[NSLayoutConstraint constraintWithItem:compassContainer
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationGreaterThanOrEqual
toItem:viewController.topLayoutGuide
attribute:NSLayoutAttributeBottom
multiplier:1
constant:5]];
}
[compassContainerConstraints addObject:
[NSLayoutConstraint constraintWithItem:compassContainer
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationGreaterThanOrEqual
toItem:self
attribute:NSLayoutAttributeTop
multiplier:1
constant:5]];
[compassContainerConstraints addObject:
[NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:compassContainer
attribute:NSLayoutAttributeTrailing
multiplier:1
constant:5]];
[compassContainerConstraints addObject:
[NSLayoutConstraint constraintWithItem:compassContainer
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1
constant:self.compassView.image.size.width]];
[compassContainerConstraints addObject:
[NSLayoutConstraint constraintWithItem:compassContainer
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1
constant:self.compassView.image.size.height]];
[constraintParentView addConstraints:compassContainerConstraints];
// logo bug
//
[self.logoView removeConstraints:self.logoViewConstraints];
[self.logoViewConstraints removeAllObjects];
if (viewController)
{
[self.logoViewConstraints addObject:
[NSLayoutConstraint constraintWithItem:viewController.bottomLayoutGuide
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationGreaterThanOrEqual
toItem:self.logoView
attribute:NSLayoutAttributeBaseline
multiplier:1
constant:8]];
}
[self.logoViewConstraints addObject:
[NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationGreaterThanOrEqual
toItem:self.logoView
attribute:NSLayoutAttributeBaseline
multiplier:1
constant:8]];
[self.logoViewConstraints addObject:
[NSLayoutConstraint constraintWithItem:self.logoView
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeLeading
multiplier:1
constant:8]];
[constraintParentView addConstraints:self.logoViewConstraints];
// attribution button
//
[self.attributionButton removeConstraints:self.attributionButtonConstraints];
[self.attributionButtonConstraints removeAllObjects];
if (viewController)
{
[self.attributionButtonConstraints addObject:
[NSLayoutConstraint constraintWithItem:viewController.bottomLayoutGuide
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationGreaterThanOrEqual
toItem:self.attributionButton
attribute:NSLayoutAttributeBaseline
multiplier:1
constant:8]];
}
[self.attributionButtonConstraints addObject:
[NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationGreaterThanOrEqual
toItem:self.attributionButton
attribute:NSLayoutAttributeBaseline
multiplier:1
constant:8]];
[self.attributionButtonConstraints addObject:
[NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:self.attributionButton
attribute:NSLayoutAttributeTrailing
multiplier:1
constant:8]];
[constraintParentView addConstraints:self.attributionButtonConstraints];
[super updateConstraints];
}
// This is the delegate of the GLKView object's display call.
- (void)glkView:(__unused GLKView *)view drawInRect:(__unused CGRect)rect
{
if ( ! self.isDormant)
{
CGFloat zoomFactor = _mbglMap->getMaxZoom() - _mbglMap->getMinZoom() + 1;
CGFloat cpuFactor = (CGFloat)[[NSProcessInfo processInfo] processorCount];
CGFloat memoryFactor = (CGFloat)[[NSProcessInfo processInfo] physicalMemory] / 1000 / 1000 / 1000;
CGFloat sizeFactor = ((CGFloat)_mbglMap->getWidth() / mbgl::util::tileSize) *
((CGFloat)_mbglMap->getHeight() / mbgl::util::tileSize);
NSUInteger cacheSize = zoomFactor * cpuFactor * memoryFactor * sizeFactor * 0.5;
_mbglMap->setSourceTileCacheSize(cacheSize);
_mbglMap->renderSync();
[self updateUserLocationAnnotationView];
}
}
// This gets called when the view dimension changes, e.g. because the device is being rotated.
- (void)layoutSubviews
{
[super layoutSubviews];
if ( ! _isTargetingInterfaceBuilder)
{
_mbglMap->update(mbgl::Update::Dimensions);
}
if (self.attributionSheet.visible)
{
[self.attributionSheet dismissWithClickedButtonIndex:self.attributionSheet.cancelButtonIndex animated:YES];
}
if (self.compassView.alpha)
{
[self updateHeadingForDeviceOrientation];
[self updateCompass];
[self updateUserLocationAnnotationView];
}
}
#pragma mark - Life Cycle -
- (void)updateFromDisplayLink
{
MGLAssertIsMainThread();
if (_needsDisplayRefresh)
{
_needsDisplayRefresh = NO;
[self.glView display];
}
}
- (void)invalidate
{
MGLAssertIsMainThread();
_needsDisplayRefresh = YES;
}
- (void)willTerminate
{
MGLAssertIsMainThread();
if ( ! self.isDormant)
{
self.dormant = YES;
_mbglMap->pause();
[self.glView deleteDrawable];
}
}
- (void)sleepGL:(__unused NSNotification *)notification
{
MGLAssertIsMainThread();
if ( ! self.isDormant)
{
self.dormant = YES;
[MGLMapboxEvents flush];
if ( ! self.glSnapshotView)
{
self.glSnapshotView = [[UIImageView alloc] initWithFrame:self.glView.frame];
self.glSnapshotView.autoresizingMask = self.glView.autoresizingMask;
self.glSnapshotView.contentMode = UIViewContentModeCenter;
[self insertSubview:self.glSnapshotView aboveSubview:self.glView];
}
self.glSnapshotView.image = self.glView.snapshot;
self.glSnapshotView.hidden = NO;
if (_mbglMap->getDebug() && [self.glSnapshotView.subviews count] == 0)
{
UIView *snapshotTint = [[UIView alloc] initWithFrame:self.glSnapshotView.bounds];
snapshotTint.autoresizingMask = self.glSnapshotView.autoresizingMask;
snapshotTint.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.25];
[self.glSnapshotView addSubview:snapshotTint];
}
_mbglMap->pause();
[self.glView deleteDrawable];
}
}
- (void)wakeGL:(__unused NSNotification *)notification
{
MGLAssertIsMainThread();
if (self.isDormant && [UIApplication sharedApplication].applicationState != UIApplicationStateBackground)
{
self.dormant = NO;
[self createGLView];
[MGLMapboxEvents validate];
self.glSnapshotView.hidden = YES;
[self.glSnapshotView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
[self.glView bindDrawable];
_mbglMap->resume();
}
}
- (void)tintColorDidChange
{
for (UIView *subview in self.subviews) [self updateTintColorForView:subview];
}
- (void)updateTintColorForView:(UIView *)view
{
if ([view respondsToSelector:@selector(setTintColor:)]) view.tintColor = self.tintColor;
for (UIView *subview in view.subviews) [self updateTintColorForView:subview];
}
#pragma mark - Gestures -
- (void)handleCompassTapGesture:(__unused id)sender
{
[self resetNorthAnimated:YES];
if (self.userTrackingMode == MGLUserTrackingModeFollowWithHeading ||
self.userTrackingMode == MGLUserTrackingModeFollowWithCourse)
{
self.userTrackingMode = MGLUserTrackingModeFollow;
}
}
- (void)touchesBegan:(__unused NS_SET_OF(UITouch *) *)touches withEvent:(__unused UIEvent *)event
{
_mbglMap->cancelTransitions();
_mbglMap->setGestureInProgress(false);
self.animatingGesture = NO;
}
- (void)handlePanGesture:(UIPanGestureRecognizer *)pan
{
if ( ! self.isScrollEnabled) return;
_mbglMap->cancelTransitions();
if (pan.state == UIGestureRecognizerStateBegan)
{
[self trackGestureEvent:MGLEventGesturePanStart forRecognizer:pan];
_mbglMap->setGestureInProgress(true);
self.centerPoint = CGPointMake(0, 0);
self.userTrackingMode = MGLUserTrackingModeNone;
}
else if (pan.state == UIGestureRecognizerStateChanged)
{
CGPoint delta = CGPointMake([pan translationInView:pan.view].x - self.centerPoint.x,
[pan translationInView:pan.view].y - self.centerPoint.y);
double flippedY = self.bounds.size.height - [pan locationInView:pan.view].y;
_mbglMap->setLatLng(
_mbglMap->latLngForPixel(mbgl::PrecisionPoint(
[pan locationInView:pan.view].x - delta.x,
flippedY + delta.y)),
mbgl::PrecisionPoint(
[pan locationInView:pan.view].x,
flippedY));
self.centerPoint = CGPointMake(self.centerPoint.x + delta.x, self.centerPoint.y + delta.y);
[self notifyMapChange:mbgl::MapChangeRegionIsChanging];
}
else if (pan.state == UIGestureRecognizerStateEnded || pan.state == UIGestureRecognizerStateCancelled)
{
CGPoint velocity = [pan velocityInView:pan.view];
if (sqrtf(velocity.x * velocity.x + velocity.y * velocity.y) < 100)
{
// Not enough velocity to overcome friction
velocity = CGPointZero;
}
CGFloat duration = UIScrollViewDecelerationRateNormal;
if ( ! CGPointEqualToPoint(velocity, CGPointZero))
{
CGPoint offset = CGPointMake(velocity.x * duration / 4, velocity.y * duration / 4);
_mbglMap->moveBy({ offset.x, offset.y }, durationInSeconds(duration));
}
_mbglMap->setGestureInProgress(false);
if ( ! CGPointEqualToPoint(velocity, CGPointZero))
{
self.animatingGesture = YES;
__weak MGLMapView *weakSelf = self;
[self animateWithDelay:duration animations:^
{
weakSelf.animatingGesture = NO;
[weakSelf notifyMapChange:mbgl::MapChangeRegionDidChangeAnimated];
}];
}
else
{
[self notifyMapChange:mbgl::MapChangeRegionDidChange];
}
// metrics: pan end
CGPoint pointInView = CGPointMake([pan locationInView:pan.view].x, [pan locationInView:pan.view].y);
CLLocationCoordinate2D panCoordinate = [self convertPoint:pointInView toCoordinateFromView:pan.view];
int zoom = round([self zoomLevel]);
[MGLMapboxEvents pushEvent:MGLEventTypeMapDragEnd withAttributes:@{
MGLEventKeyLatitude: @(panCoordinate.latitude),
MGLEventKeyLongitude: @(panCoordinate.longitude),
MGLEventKeyZoomLevel: @(zoom)
}];
}
}
- (void)handlePinchGesture:(UIPinchGestureRecognizer *)pinch
{
if ( ! self.isZoomEnabled) return;
if (_mbglMap->getZoom() <= _mbglMap->getMinZoom() && pinch.scale < 1) return;
_mbglMap->cancelTransitions();
if (pinch.state == UIGestureRecognizerStateBegan)
{
[self trackGestureEvent:MGLEventGesturePinchStart forRecognizer:pinch];
_mbglMap->setGestureInProgress(true);
self.scale = _mbglMap->getScale();
self.userTrackingMode = MGLUserTrackingModeNone;
}
else if (pinch.state == UIGestureRecognizerStateChanged)
{
CGFloat newScale = self.scale * pinch.scale;
if (log2(newScale) < _mbglMap->getMinZoom()) return;
mbgl::PrecisionPoint center([pinch locationInView:pinch.view].x,
[pinch locationInView:pinch.view].y);
_mbglMap->setScale(newScale, center);
[self notifyMapChange:mbgl::MapChangeRegionIsChanging];
}
else if (pinch.state == UIGestureRecognizerStateEnded || pinch.state == UIGestureRecognizerStateCancelled)
{
CGFloat velocity = pinch.velocity;
if (isnan(velocity))
{
// UIPinchGestureRecognizer sometimes returns NaN for the velocity
velocity = 0;
}
if (velocity > -0.5 && velocity < 3)
{
velocity = 0;
}
CGFloat duration = velocity > 0 ? 1 : 0.25;
CGFloat scale = self.scale * pinch.scale;
CGFloat newScale = scale;
if (velocity >= 0)
{
newScale += scale * velocity * duration * 0.1;
}
else
{
newScale += scale / (velocity * duration) * 0.1;
}
if (newScale <= 0 || log2(newScale) < _mbglMap->getMinZoom())
{
velocity = 0;
}
if (velocity)
{
CGPoint pinchCenter = [pinch locationInView:pinch.view];
mbgl::PrecisionPoint center(pinchCenter.x, pinchCenter.y);
_mbglMap->setScale(newScale, center, durationInSeconds(duration));
}
_mbglMap->setGestureInProgress(false);
[self unrotateIfNeededAnimated:YES];
if (velocity)
{
self.animatingGesture = YES;
__weak MGLMapView *weakSelf = self;
[self animateWithDelay:duration animations:^
{
weakSelf.animatingGesture = NO;
[weakSelf notifyMapChange:mbgl::MapChangeRegionDidChangeAnimated];
}];
}
else
{
[self notifyMapChange:mbgl::MapChangeRegionDidChange];
}
}
}
- (void)handleRotateGesture:(UIRotationGestureRecognizer *)rotate
{
if ( ! self.isRotateEnabled) return;