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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
|
#import "MapDocument.h"
#import "AppDelegate.h"
#import "LimeGreenStyleLayer.h"
#import "DroppedPinAnnotation.h"
#import "MGLMapsnapshotter.h"
#import "MGLStyle+MBXAdditions.h"
#import "MGLVectorSource_Private.h"
#import <Mapbox/Mapbox.h>
static NSString * const MGLDroppedPinAnnotationImageIdentifier = @"dropped";
static const CLLocationCoordinate2D WorldTourDestinations[] = {
{ .latitude = 38.9131982, .longitude = -77.0325453144239 },
{ .latitude = 37.7757368, .longitude = -122.4135302 },
{ .latitude = 12.9810816, .longitude = 77.6368034 },
{ .latitude = -13.15589555, .longitude = -74.2178961777998 },
};
NS_ARRAY_OF(id <MGLAnnotation>) *MBXFlattenedShapes(NS_ARRAY_OF(id <MGLAnnotation>) *shapes) {
NSMutableArray *flattenedShapes = [NSMutableArray arrayWithCapacity:shapes.count];
for (id <MGLAnnotation> shape in shapes) {
NSArray *subshapes;
if ([shape isKindOfClass:[MGLMultiPolyline class]]) {
subshapes = [(MGLMultiPolyline *)shape polylines];
} else if ([shape isKindOfClass:[MGLMultiPolygon class]]) {
subshapes = [(MGLMultiPolygon *)shape polygons];
} else if ([shape isKindOfClass:[MGLPointCollection class]]) {
NSUInteger pointCount = [(MGLPointCollection *)shape pointCount];
CLLocationCoordinate2D *coordinates = [(MGLPointCollection *)shape coordinates];
NSMutableArray *pointAnnotations = [NSMutableArray arrayWithCapacity:pointCount];
for (NSUInteger i = 0; i < pointCount; i++) {
MGLPointAnnotation *pointAnnotation = [[MGLPointAnnotation alloc] init];
pointAnnotation.coordinate = coordinates[i];
[pointAnnotations addObject:pointAnnotation];
}
subshapes = pointAnnotations;
} else if ([shape isKindOfClass:[MGLShapeCollection class]]) {
subshapes = MBXFlattenedShapes([(MGLShapeCollection *)shape shapes]);
}
if (subshapes) {
[flattenedShapes addObjectsFromArray:subshapes];
} else {
[flattenedShapes addObject:shape];
}
}
return flattenedShapes;
}
@interface MapDocument () <NSWindowDelegate, NSSharingServicePickerDelegate, NSMenuDelegate, NSSplitViewDelegate, MGLMapViewDelegate, MGLComputedShapeSourceDataSource>
@property (weak) IBOutlet NSArrayController *styleLayersArrayController;
@property (weak) IBOutlet NSTableView *styleLayersTableView;
@property (weak) IBOutlet NSMenu *mapViewContextMenu;
@property (weak) IBOutlet NSSplitView *splitView;
@end
@implementation MapDocument {
/// Style URL inherited from an existing document at the time this document
/// was created.
NSURL *_inheritedStyleURL;
NSPoint _mouseLocationForMapViewContextMenu;
NSUInteger _droppedPinCounter;
NSNumberFormatter *_spellOutNumberFormatter;
BOOL _isLocalizingLabels;
BOOL _showsToolTipsOnDroppedPins;
BOOL _randomizesCursorsOnDroppedPins;
BOOL _isTouringWorld;
BOOL _isShowingPolygonAndPolylineAnnotations;
BOOL _isShowingAnimatedAnnotation;
// Snapshotter
MGLMapSnapshotter* snapshotter;
}
#pragma mark Lifecycle
- (NSString *)windowNibName {
return @"MapDocument";
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)windowControllerWillLoadNib:(NSWindowController *)windowController {
NSDocument *currentDocument = [NSDocumentController sharedDocumentController].currentDocument;
if ([currentDocument isKindOfClass:[MapDocument class]]) {
_inheritedStyleURL = [(MapDocument *)currentDocument mapView].styleURL;
}
}
- (void)windowControllerDidLoadNib:(NSWindowController *)controller {
[super windowControllerDidLoadNib:controller];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(userDefaultsDidChange:)
name:NSUserDefaultsDidChangeNotification
object:nil];
_spellOutNumberFormatter = [[NSNumberFormatter alloc] init];
NSPressGestureRecognizer *pressGestureRecognizer = [[NSPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlePressGesture:)];
[self.mapView addGestureRecognizer:pressGestureRecognizer];
[self.splitView setPosition:0 ofDividerAtIndex:0];
[self applyPendingState];
}
- (NSWindow *)window {
return self.windowControllers.firstObject.window;
}
- (void)userDefaultsDidChange:(NSNotification *)notification {
NSUserDefaults *userDefaults = notification.object;
NSString *accessToken = [userDefaults stringForKey:MGLMapboxAccessTokenDefaultsKey];
if (![accessToken isEqualToString:[MGLAccountManager accessToken]]) {
[MGLAccountManager setAccessToken:accessToken];
[self reload:self];
}
}
#pragma mark NSWindowDelegate methods
- (void)window:(NSWindow *)window willEncodeRestorableState:(NSCoder *)state {
[state encodeObject:self.mapView.styleURL forKey:@"MBXMapViewStyleURL"];
[state encodeBool:_isLocalizingLabels forKey:@"MBXLocalizeLabels"];
}
- (void)window:(NSWindow *)window didDecodeRestorableState:(NSCoder *)state {
self.mapView.styleURL = [state decodeObjectForKey:@"MBXMapViewStyleURL"];
_isLocalizingLabels = [state decodeBoolForKey:@"MBXLocalizeLabels"];
}
#pragma mark Services
- (IBAction)showShareMenu:(id)sender {
NSSharingServicePicker *picker = [[NSSharingServicePicker alloc] initWithItems:@[self.shareURL]];
picker.delegate = self;
[picker showRelativeToRect:[sender bounds] ofView:sender preferredEdge:NSMinYEdge];
}
- (NSURL *)shareURL {
NSArray *components = self.mapView.styleURL.pathComponents;
MGLMapCamera *camera = self.mapView.camera;
return [NSURL URLWithString:
[NSString stringWithFormat:@"https://api.mapbox.com/styles/v1/%@/%@.html?access_token=%@#%.2f/%.5f/%.5f/%.f/%.f",
components[1], components[2], [MGLAccountManager accessToken],
self.mapView.zoomLevel, camera.centerCoordinate.latitude, camera.centerCoordinate.longitude,
camera.heading, camera.pitch]];
}
#pragma mark File methods
- (IBAction)takeSnapshot:(id)sender {
MGLMapCamera *camera = self.mapView.camera;
MGLMapSnapshotOptions *options = [[MGLMapSnapshotOptions alloc] initWithStyleURL:self.mapView.styleURL camera:camera size:self.mapView.bounds.size];
options.zoomLevel = self.mapView.zoomLevel;
// Create and start the snapshotter
snapshotter = [[MGLMapSnapshotter alloc] initWithOptions:options];
[snapshotter startWithCompletionHandler:^(MGLMapSnapshot *snapshot, NSError *error) {
if (error) {
NSLog(@"Could not load snapshot: %@", error.localizedDescription);
} else {
// Set the default name for the file and show the panel.
NSSavePanel *panel = [NSSavePanel savePanel];
panel.nameFieldStringValue = [self.mapView.styleURL.lastPathComponent.stringByDeletingPathExtension stringByAppendingPathExtension:@"png"];
panel.allowedFileTypes = [@[(NSString *)kUTTypePNG] arrayByAddingObjectsFromArray:[NSBitmapImageRep imageUnfilteredTypes]];
[panel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
if (result == NSFileHandlingPanelOKButton) {
// Write the contents in the new format.
NSURL *fileURL = panel.URL;
NSBitmapImageRep *bitmapRep;
for (NSImageRep *imageRep in snapshot.image.representations) {
if ([imageRep isKindOfClass:[NSBitmapImageRep class]]) {
bitmapRep = (NSBitmapImageRep *)imageRep;
break; // stop on first bitmap rep we find
}
}
if (!bitmapRep) {
bitmapRep = [NSBitmapImageRep imageRepWithData:snapshot.image.TIFFRepresentation];
}
CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)fileURL.pathExtension, NULL /* inConformingToUTI */);
NSBitmapImageFileType fileType = NSTIFFFileType;
if (UTTypeConformsTo(uti, kUTTypePNG)) {
fileType = NSPNGFileType;
} else if (UTTypeConformsTo(uti, kUTTypeGIF)) {
fileType = NSGIFFileType;
} else if (UTTypeConformsTo(uti, kUTTypeJPEG2000)) {
fileType = NSJPEG2000FileType;
} else if (UTTypeConformsTo(uti, kUTTypeJPEG)) {
fileType = NSJPEGFileType;
} else if (UTTypeConformsTo(uti, kUTTypeBMP)) {
fileType = NSBitmapImageFileTypeBMP;
}
NSData *imageData = [bitmapRep representationUsingType:fileType properties:@{}];
[imageData writeToURL:fileURL atomically:NO];
}
}];
}
snapshotter = nil;
}];
}
#pragma mark View methods
- (IBAction)showStyle:(id)sender {
NSInteger tag = -1;
if ([sender isKindOfClass:[NSMenuItem class]]) {
tag = [sender tag];
} else if ([sender isKindOfClass:[NSPopUpButton class]]) {
tag = [sender selectedTag];
}
NSURL *styleURL;
switch (tag) {
case 1:
styleURL = [MGLStyle streetsStyleURL];
break;
case 2:
styleURL = [MGLStyle outdoorsStyleURL];
break;
case 3:
styleURL = [MGLStyle lightStyleURL];
break;
case 4:
styleURL = [MGLStyle darkStyleURL];
break;
case 5:
styleURL = [MGLStyle satelliteStyleURL];
break;
case 6:
styleURL = [MGLStyle satelliteStreetsStyleURL];
break;
case 7:
styleURL = [NSURL URLWithString:@"mapbox://styles/mapbox/traffic-day-v2"];
break;
case 8:
styleURL = [NSURL URLWithString:@"mapbox://styles/mapbox/traffic-night-v2"];
break;
default:
NSAssert(NO, @"Cannot set style from control with tag %li", (long)tag);
break;
}
[self.undoManager removeAllActionsWithTarget:self];
self.mapView.styleURL = styleURL;
[self.window.toolbar validateVisibleItems];
}
- (IBAction)chooseCustomStyle:(id)sender {
NSAlert *alert = [[NSAlert alloc] init];
alert.messageText = @"Apply custom style";
alert.informativeText = @"Enter the URL to a JSON file that conforms to the Mapbox Style Specification, such as a style designed in Mapbox Studio:";
NSTextField *textField = [[NSTextField alloc] initWithFrame:NSZeroRect];
[textField sizeToFit];
NSRect textFieldFrame = textField.frame;
textFieldFrame.size.width = 300;
textField.frame = textFieldFrame;
NSURL *savedURL = [[NSUserDefaults standardUserDefaults] URLForKey:@"MBXCustomStyleURL"];
if (savedURL) {
textField.stringValue = savedURL.absoluteString;
}
alert.accessoryView = textField;
[alert addButtonWithTitle:@"Apply"];
[alert addButtonWithTitle:@"Cancel"];
if ([alert runModal] == NSAlertFirstButtonReturn) {
[self.undoManager removeAllActionsWithTarget:self];
self.mapView.styleURL = [NSURL URLWithString:textField.stringValue];
[[NSUserDefaults standardUserDefaults] setURL:self.mapView.styleURL forKey:@"MBXCustomStyleURL"];
[self.window.toolbar validateVisibleItems];
}
}
- (IBAction)zoomIn:(id)sender {
[self.mapView setZoomLevel:round(self.mapView.zoomLevel) + 1 animated:YES];
}
- (IBAction)zoomOut:(id)sender {
[self.mapView setZoomLevel:round(self.mapView.zoomLevel) - 1 animated:YES];
}
- (IBAction)snapToNorth:(id)sender {
[self.mapView setDirection:0 animated:YES];
}
- (IBAction)reload:(id)sender {
[self.undoManager removeAllActionsWithTarget:self];
[self.mapView reloadStyle:sender];
}
/**
Show or hide the Layers sidebar.
*/
- (IBAction)toggleLayers:(id)sender {
BOOL isShown = ![self.splitView isSubviewCollapsed:self.splitView.arrangedSubviews.firstObject];
[NSAnimationContext runAnimationGroup:^(NSAnimationContext * _Nonnull context) {
context.allowsImplicitAnimation = YES;
[self.splitView setPosition:isShown ? 0 : 100 ofDividerAtIndex:0];
[self.window.toolbar validateVisibleItems];
} completionHandler:nil];
}
/**
Show or hide the selected layers.
*/
- (IBAction)toggleStyleLayers:(id)sender {
NSInteger clickedRow = self.styleLayersTableView.clickedRow;
NSIndexSet *indices = self.styleLayersTableView.selectedRowIndexes;
if (clickedRow >= 0 && ![indices containsIndex:clickedRow]) {
indices = [NSIndexSet indexSetWithIndex:clickedRow];
}
[self toggleStyleLayersAtArrangedObjectIndexes:indices];
}
- (void)toggleStyleLayersAtArrangedObjectIndexes:(NSIndexSet *)indices {
NS_ARRAY_OF(MGLStyleLayer *) *layers = [self.mapView.style.reversedLayers objectsAtIndexes:indices];
BOOL isVisible = layers.firstObject.visible;
[self.undoManager registerUndoWithTarget:self handler:^(MapDocument * _Nonnull target) {
[target toggleStyleLayersAtArrangedObjectIndexes:indices];
}];
if (!self.undoManager.undoing) {
NSString *actionName;
if (indices.count == 1) {
actionName = [NSString stringWithFormat:@"%@ Layer “%@”", isVisible ? @"Hide" : @"Show", layers.firstObject.identifier];
} else {
actionName = [NSString stringWithFormat:@"%@ %@ Layers", isVisible ? @"Hide" : @"Show",
[NSNumberFormatter localizedStringFromNumber:@(indices.count)
numberStyle:NSNumberFormatterDecimalStyle]];
}
[self.undoManager setActionIsDiscardable:YES];
[self.undoManager setActionName:actionName];
}
for (MGLStyleLayer *layer in layers) {
layer.visible = !isVisible;
}
NSIndexSet *columnIndices = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 2)];
[self.styleLayersTableView reloadDataForRowIndexes:indices columnIndexes:columnIndices];
}
- (IBAction)deleteStyleLayers:(id)sender {
NSInteger clickedRow = self.styleLayersTableView.clickedRow;
NSIndexSet *indices = self.styleLayersTableView.selectedRowIndexes;
if (clickedRow >= 0 && ![indices containsIndex:clickedRow]) {
indices = [NSIndexSet indexSetWithIndex:clickedRow];
}
[self deleteStyleLayersAtArrangedObjectIndexes:indices];
}
- (void)insertStyleLayers:(NS_ARRAY_OF(MGLStyleLayer *) *)layers atArrangedObjectIndexes:(NSIndexSet *)indices {
[self.undoManager registerUndoWithTarget:self handler:^(id _Nonnull target) {
[self deleteStyleLayersAtArrangedObjectIndexes:indices];
}];
if (!self.undoManager.undoing) {
NSString *actionName;
if (indices.count == 1) {
actionName = [NSString stringWithFormat:@"Add Layer “%@”", layers.firstObject.identifier];
} else {
actionName = [NSString stringWithFormat:@"Add %@ Layers",
[NSNumberFormatter localizedStringFromNumber:@(indices.count) numberStyle:NSNumberFormatterDecimalStyle]];
}
[self.undoManager setActionName:actionName];
}
[self.styleLayersArrayController insertObjects:layers atArrangedObjectIndexes:indices];
}
- (void)deleteStyleLayersAtArrangedObjectIndexes:(NSIndexSet *)indices {
NS_ARRAY_OF(MGLStyleLayer *) *layers = [self.mapView.style.reversedLayers objectsAtIndexes:indices];
[self.undoManager registerUndoWithTarget:self handler:^(id _Nonnull target) {
[self insertStyleLayers:layers atArrangedObjectIndexes:indices];
}];
if (!self.undoManager.undoing) {
NSString *actionName;
if (indices.count == 1) {
actionName = [NSString stringWithFormat:@"Delete Layer “%@”", layers.firstObject.identifier];
} else {
actionName = [NSString stringWithFormat:@"Delete %@ Layers",
[NSNumberFormatter localizedStringFromNumber:@(indices.count) numberStyle:NSNumberFormatterDecimalStyle]];
}
[self.undoManager setActionName:actionName];
}
[self.styleLayersArrayController removeObjectsAtArrangedObjectIndexes:indices];
}
- (IBAction)setLabelLanguage:(NSMenuItem *)sender {
_isLocalizingLabels = sender.tag;
[self reload:sender];
}
- (void)updateLabels {
self.mapView.style.localizesLabels = _isLocalizingLabels;
}
- (void)applyPendingState {
if (_inheritedStyleURL) {
self.mapView.styleURL = _inheritedStyleURL;
_inheritedStyleURL = nil;
}
AppDelegate *appDelegate = (AppDelegate *)NSApp.delegate;
if (appDelegate.pendingStyleURL) {
self.mapView.styleURL = appDelegate.pendingStyleURL;
}
if (appDelegate.pendingCamera) {
if (appDelegate.pendingZoomLevel >= 0) {
self.mapView.zoomLevel = appDelegate.pendingZoomLevel;
appDelegate.pendingCamera.altitude = self.mapView.camera.altitude;
}
self.mapView.camera = appDelegate.pendingCamera;
appDelegate.pendingZoomLevel = -1;
appDelegate.pendingCamera = nil;
}
if (!MGLCoordinateBoundsIsEmpty(appDelegate.pendingVisibleCoordinateBounds)) {
self.mapView.visibleCoordinateBounds = appDelegate.pendingVisibleCoordinateBounds;
appDelegate.pendingVisibleCoordinateBounds = (MGLCoordinateBounds){ { 0, 0 }, { 0, 0 } };
}
if (appDelegate.pendingDebugMask) {
self.mapView.debugMask = appDelegate.pendingDebugMask;
}
if (appDelegate.pendingMinimumZoomLevel >= 0) {
self.mapView.zoomLevel = MAX(appDelegate.pendingMinimumZoomLevel, self.mapView.zoomLevel);
appDelegate.pendingMaximumZoomLevel = -1;
}
if (appDelegate.pendingMaximumZoomLevel >= 0) {
self.mapView.zoomLevel = MIN(appDelegate.pendingMaximumZoomLevel, self.mapView.zoomLevel);
appDelegate.pendingMaximumZoomLevel = -1;
}
// Temporarily set the display name to the default center coordinate instead
// of “Untitled” until the binding kicks in.
NSValue *coordinateValue = [NSValue valueWithMGLCoordinate:self.mapView.centerCoordinate];
NSString *coordinateString = [[NSValueTransformer valueTransformerForName:@"LocationCoordinate2DTransformer"]
transformedValue:coordinateValue];
self.displayName = [NSString stringWithFormat:@"%@ @ %f", coordinateString, _mapView.zoomLevel];
}
#pragma mark Debug methods
- (IBAction)toggleTileBoundaries:(id)sender {
self.mapView.debugMask ^= MGLMapDebugTileBoundariesMask;
}
- (IBAction)toggleTileInfo:(id)sender {
self.mapView.debugMask ^= MGLMapDebugTileInfoMask;
}
- (IBAction)toggleTileTimestamps:(id)sender {
self.mapView.debugMask ^= MGLMapDebugTimestampsMask;
}
- (IBAction)toggleCollisionBoxes:(id)sender {
self.mapView.debugMask ^= MGLMapDebugCollisionBoxesMask;
}
- (IBAction)toggleOverdrawVisualization:(id)sender {
self.mapView.debugMask ^= MGLMapDebugOverdrawVisualizationMask;
}
- (IBAction)showColorBuffer:(id)sender {
self.mapView.debugMask &= ~MGLMapDebugStencilBufferMask;
self.mapView.debugMask &= ~MGLMapDebugDepthBufferMask;
}
- (IBAction)showStencilBuffer:(id)sender {
self.mapView.debugMask &= ~MGLMapDebugDepthBufferMask;
self.mapView.debugMask |= MGLMapDebugStencilBufferMask;
}
- (IBAction)showDepthBuffer:(id)sender {
self.mapView.debugMask &= ~MGLMapDebugStencilBufferMask;
self.mapView.debugMask |= MGLMapDebugDepthBufferMask;
}
- (IBAction)toggleShowsToolTipsOnDroppedPins:(id)sender {
_showsToolTipsOnDroppedPins = !_showsToolTipsOnDroppedPins;
}
- (IBAction)toggleRandomizesCursorsOnDroppedPins:(id)sender {
_randomizesCursorsOnDroppedPins = !_randomizesCursorsOnDroppedPins;
}
- (IBAction)dropManyPins:(id)sender {
[self removeAllAnnotations:sender];
NSRect bounds = self.mapView.bounds;
NSMutableArray *annotations = [NSMutableArray array];
for (CGFloat x = NSMinX(bounds); x < NSMaxX(bounds); x += arc4random_uniform(50)) {
for (CGFloat y = NSMaxY(bounds); y >= NSMinY(bounds); y -= arc4random_uniform(100)) {
[annotations addObject:[self pinAtPoint:NSMakePoint(x, y)]];
}
}
[NSTimer scheduledTimerWithTimeInterval:1.0/60.0
target:self
selector:@selector(dropOneOfManyPins:)
userInfo:annotations
repeats:YES];
}
- (void)dropOneOfManyPins:(NSTimer *)timer {
NSMutableArray *annotations = timer.userInfo;
NSUInteger numberOfAnnotationsToAdd = 50;
if (annotations.count < numberOfAnnotationsToAdd) {
numberOfAnnotationsToAdd = annotations.count;
}
NSArray *annotationsToAdd = [annotations subarrayWithRange:
NSMakeRange(0, numberOfAnnotationsToAdd)];
[self.mapView addAnnotations:annotationsToAdd];
[annotations removeObjectsInRange:NSMakeRange(0, numberOfAnnotationsToAdd)];
if (!annotations.count) {
[timer invalidate];
}
}
- (IBAction)showAllAnnotations:(id)sender {
[self.mapView showAnnotations:self.mapView.annotations animated:YES];
}
- (IBAction)removeAllAnnotations:(id)sender {
[self.mapView removeAnnotations:self.mapView.annotations];
_isShowingPolygonAndPolylineAnnotations = NO;
_isShowingAnimatedAnnotation = NO;
}
- (IBAction)startWorldTour:(id)sender {
_isTouringWorld = YES;
[self removeAllAnnotations:sender];
NSUInteger numberOfAnnotations = sizeof(WorldTourDestinations) / sizeof(WorldTourDestinations[0]);
NSMutableArray *annotations = [NSMutableArray arrayWithCapacity:numberOfAnnotations];
for (NSUInteger i = 0; i < numberOfAnnotations; i++) {
MGLPointAnnotation *annotation = [[MGLPointAnnotation alloc] init];
annotation.coordinate = WorldTourDestinations[i];
[annotations addObject:annotation];
}
[self.mapView addAnnotations:annotations];
[self continueWorldTourWithRemainingAnnotations:annotations];
}
- (void)continueWorldTourWithRemainingAnnotations:(NS_MUTABLE_ARRAY_OF(MGLPointAnnotation *) *)annotations {
MGLPointAnnotation *nextAnnotation = annotations.firstObject;
if (!nextAnnotation || !_isTouringWorld) {
_isTouringWorld = NO;
return;
}
[annotations removeObjectAtIndex:0];
MGLMapCamera *camera = [MGLMapCamera cameraLookingAtCenterCoordinate:nextAnnotation.coordinate
fromDistance:0
pitch:arc4random_uniform(60)
heading:arc4random_uniform(360)];
__weak MapDocument *weakSelf = self;
[self.mapView flyToCamera:camera completionHandler:^{
MapDocument *strongSelf = weakSelf;
[strongSelf performSelector:@selector(continueWorldTourWithRemainingAnnotations:)
withObject:annotations
afterDelay:2];
}];
}
- (IBAction)stopWorldTour:(id)sender {
_isTouringWorld = NO;
// Any programmatic viewpoint change cancels outstanding animations.
self.mapView.camera = self.mapView.camera;
}
- (IBAction)drawPolygonAndPolyLineAnnotations:(id)sender {
if (_isShowingPolygonAndPolylineAnnotations) {
[self removeAllAnnotations:sender];
return;
}
_isShowingPolygonAndPolylineAnnotations = YES;
// Pacific Northwest triangle
CLLocationCoordinate2D triangleCoordinates[3] = {
CLLocationCoordinate2DMake(44, -122),
CLLocationCoordinate2DMake(46, -122),
CLLocationCoordinate2DMake(46, -121)
};
MGLPolygon *triangle = [MGLPolygon polygonWithCoordinates:triangleCoordinates count:3];
[self.mapView addAnnotation:triangle];
// West coast line
CLLocationCoordinate2D lineCoordinates[4] = {
CLLocationCoordinate2DMake(47.6025, -122.3327),
CLLocationCoordinate2DMake(45.5189, -122.6726),
CLLocationCoordinate2DMake(37.7790, -122.4177),
CLLocationCoordinate2DMake(34.0532, -118.2349)
};
MGLPolyline *line = [MGLPolyline polylineWithCoordinates:lineCoordinates count:4];
[self.mapView addAnnotation:line];
}
- (IBAction)drawAnimatedAnnotation:(id)sender {
DroppedPinAnnotation *annotation = [[DroppedPinAnnotation alloc] init];
[self.mapView addAnnotation:annotation];
_isShowingAnimatedAnnotation = YES;
[NSTimer scheduledTimerWithTimeInterval:1.0/60.0
target:self
selector:@selector(updateAnimatedAnnotation:)
userInfo:annotation
repeats:YES];
}
- (void)updateAnimatedAnnotation:(NSTimer *)timer {
DroppedPinAnnotation *annotation = timer.userInfo;
double angle = timer.fireDate.timeIntervalSinceReferenceDate;
annotation.coordinate = CLLocationCoordinate2DMake(
sin(angle) * 20,
cos(angle) * 20);
}
- (IBAction) addAnimatedImageSource:(id)sender {
MGLImage *image = [[NSBundle bundleForClass:[self class]] imageForResource:@"southeast_0"];
MGLCoordinateBounds bounds = { {22.551103322318994, -90.24006072802854}, {36.928147474567794, -75.1441643681673} };
MGLImageSource *imageSource = [[MGLImageSource alloc] initWithIdentifier:@"animated-radar-source" coordinateQuad:MGLCoordinateQuadFromCoordinateBounds(bounds) image:image];
[self.mapView.style addSource:imageSource];
MGLRasterStyleLayer * imageLayer = [[MGLRasterStyleLayer alloc] initWithIdentifier:@"animated-radar-layer" source:imageSource];
[self.mapView.style addLayer:imageLayer];
[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(updateAnimatedImageSource:)
userInfo:imageSource
repeats:YES];
}
- (void)updateAnimatedImageSource:(NSTimer *)timer {
static int radarSuffix = 0;
MGLImageSource *imageSource = (MGLImageSource *)timer.userInfo;
MGLImage *image = [[NSBundle bundleForClass:[self class]] imageForResource:[NSString stringWithFormat:@"southeast_%d", radarSuffix++]];
[imageSource setValue:image forKey:@"image"];
if(radarSuffix > 3) {
radarSuffix = 0 ;
}
}
- (IBAction)insertCustomStyleLayer:(id)sender {
[self.undoManager registerUndoWithTarget:self handler:^(id _Nonnull target) {
[self removeCustomStyleLayer:sender];
}];
if (!self.undoManager.isUndoing) {
[self.undoManager setActionName:@"Add Lime Green Layer"];
}
LimeGreenStyleLayer *layer = [[LimeGreenStyleLayer alloc] initWithIdentifier:@"mbx-custom"];
MGLStyleLayer *houseNumberLayer = [self.mapView.style layerWithIdentifier:@"housenum-label"];
if (houseNumberLayer) {
[self.mapView.style insertLayer:layer belowLayer:houseNumberLayer];
} else {
[self.mapView.style addLayer:layer];
}
}
- (IBAction)removeCustomStyleLayer:(id)sender {
[self.undoManager registerUndoWithTarget:self handler:^(id _Nonnull target) {
[self insertCustomStyleLayer:sender];
}];
if (!self.undoManager.isUndoing) {
[self.undoManager setActionName:@"Delete Lime Green Layer"];
}
MGLStyleLayer *layer = [self.mapView.style layerWithIdentifier:@"mbx-custom"];
[self.mapView.style removeLayer:layer];
}
- (IBAction)insertGraticuleLayer:(id)sender {
[self.undoManager registerUndoWithTarget:self handler:^(id _Nonnull target) {
[self removeGraticuleLayer:sender];
}];
if (!self.undoManager.isUndoing) {
[self.undoManager setActionName:@"Add Graticule"];
}
MGLComputedShapeSource *source = [[MGLComputedShapeSource alloc] initWithIdentifier:@"graticule"
options:@{MGLShapeSourceOptionMaximumZoomLevel:@14}];
source.dataSource = self;
[self.mapView.style addSource:source];
MGLLineStyleLayer *lineLayer = [[MGLLineStyleLayer alloc] initWithIdentifier:@"graticule.lines"
source:source];
[self.mapView.style addLayer:lineLayer];
MGLSymbolStyleLayer *labelLayer = [[MGLSymbolStyleLayer alloc] initWithIdentifier:@"graticule.labels"
source:source];
labelLayer.text = [MGLStyleValue valueWithRawValue:@"{value}"];
[self.mapView.style addLayer:labelLayer];
}
- (IBAction)removeGraticuleLayer:(id)sender {
[self.undoManager registerUndoWithTarget:self handler:^(id _Nonnull target) {
[self insertGraticuleLayer:sender];
}];
if (!self.undoManager.isUndoing) {
[self.undoManager setActionName:@"Delete Graticule"];
}
MGLStyleLayer *layer = [self.mapView.style layerWithIdentifier:@"graticule.lines"];
[self.mapView.style removeLayer:layer];
layer = [self.mapView.style layerWithIdentifier:@"graticule.labels"];
[self.mapView.style removeLayer:layer];
MGLSource *source = [self.mapView.style sourceWithIdentifier:@"graticule"];
[self.mapView.style removeSource:source];
}
#pragma mark Offline packs
- (IBAction)addOfflinePack:(id)sender {
NSAlert *namePrompt = [[NSAlert alloc] init];
namePrompt.messageText = @"Add offline pack";
namePrompt.informativeText = @"Choose a name for the pack:";
NSTextField *nameTextField = [[NSTextField alloc] initWithFrame:NSZeroRect];
nameTextField.placeholderString = MGLStringFromCoordinateBounds(self.mapView.visibleCoordinateBounds);
[nameTextField sizeToFit];
NSRect textFieldFrame = nameTextField.frame;
textFieldFrame.size.width = 300;
nameTextField.frame = textFieldFrame;
namePrompt.accessoryView = nameTextField;
[namePrompt addButtonWithTitle:@"Add"];
[namePrompt addButtonWithTitle:@"Cancel"];
if ([namePrompt runModal] != NSAlertFirstButtonReturn) {
return;
}
id <MGLOfflineRegion> region = [[MGLTilePyramidOfflineRegion alloc] initWithStyleURL:self.mapView.styleURL bounds:self.mapView.visibleCoordinateBounds fromZoomLevel:self.mapView.zoomLevel toZoomLevel:self.mapView.maximumZoomLevel];
NSData *context = [[NSValueTransformer valueTransformerForName:@"OfflinePackNameValueTransformer"] reverseTransformedValue:nameTextField.stringValue];
[[MGLOfflineStorage sharedOfflineStorage] addPackForRegion:region withContext:context completionHandler:^(MGLOfflinePack * _Nullable pack, NSError * _Nullable error) {
if (error) {
[[NSAlert alertWithError:error] runModal];
} else {
[pack resume];
}
}];
}
#pragma mark Mouse events
- (void)handlePressGesture:(NSPressGestureRecognizer *)gestureRecognizer {
if (gestureRecognizer.state == NSGestureRecognizerStateBegan) {
NSPoint location = [gestureRecognizer locationInView:self.mapView];
if (!NSPointInRect([gestureRecognizer locationInView:self.mapView.compass], self.mapView.compass.bounds)
&& !NSPointInRect([gestureRecognizer locationInView:self.mapView.zoomControls], self.mapView.zoomControls.bounds)
&& !NSPointInRect([gestureRecognizer locationInView:self.mapView.attributionView], self.mapView.attributionView.bounds)) {
[self dropPinAtPoint:location];
}
}
}
- (IBAction)manipulateStyle:(id)sender {
MGLTransition transition = { .duration = 5, .delay = 1 };
self.mapView.style.transition = transition;
MGLStyleLayer *waterLayer = [self.mapView.style layerWithIdentifier:@"water"];
MGLStyleValue *colorFunction = [MGLStyleValue<NSColor *> valueWithInterpolationMode:MGLInterpolationModeExponential cameraStops:@{
@0.0: [MGLStyleValue<NSColor *> valueWithRawValue:[NSColor redColor]],
@10.0: [MGLStyleValue<NSColor *> valueWithRawValue:[NSColor yellowColor]],
@20.0: [MGLStyleValue<NSColor *> valueWithRawValue:[NSColor blackColor]],
} options:nil];
if ([waterLayer respondsToSelector:@selector(fillColor)]) {
[waterLayer setValue:colorFunction forKey:@"fillColor"];
} else if ([waterLayer respondsToSelector:@selector(lineColor)]) {
[waterLayer setValue:colorFunction forKey:@"lineColor"];
}
NSString *filePath = [[NSBundle bundleForClass:self.class] pathForResource:@"amsterdam" ofType:@"geojson"];
NSURL *geoJSONURL = [NSURL fileURLWithPath:filePath];
MGLShapeSource *source = [[MGLShapeSource alloc] initWithIdentifier:@"ams" URL:geoJSONURL options:nil];
[self.mapView.style addSource:source];
MGLCircleStyleLayer *circleLayer = [[MGLCircleStyleLayer alloc] initWithIdentifier:@"test" source:source];
circleLayer.circleColor = [MGLStyleValue<NSColor *> valueWithRawValue:[NSColor greenColor]];
circleLayer.circleRadius = [MGLStyleValue<NSNumber *> valueWithRawValue:[NSNumber numberWithInteger:40]];
// fillLayer.predicate = [NSPredicate predicateWithFormat:@"%K == %@", @"type", @"park"];
[self.mapView.style addLayer:circleLayer];
MGLSource *streetsSource = [self.mapView.style sourceWithIdentifier:@"composite"];
if (streetsSource) {
NSImage *image = [NSImage imageNamed:NSImageNameIChatTheaterTemplate];
[self.mapView.style setImage:image forName:NSImageNameIChatTheaterTemplate];
MGLSymbolStyleLayer *theaterLayer = [[MGLSymbolStyleLayer alloc] initWithIdentifier:@"theaters" source:streetsSource];
theaterLayer.sourceLayerIdentifier = @"poi_label";
theaterLayer.predicate = [NSPredicate predicateWithFormat:@"maki == 'theatre'"];
theaterLayer.iconImageName = [MGLStyleValue valueWithRawValue:NSImageNameIChatTheaterTemplate];
theaterLayer.iconScale = [MGLStyleValue valueWithRawValue:@2];
theaterLayer.iconColor = [MGLStyleValue valueWithInterpolationMode:MGLInterpolationModeExponential cameraStops:@{
@16.0: [MGLStyleValue valueWithRawValue:[NSColor redColor]],
@18.0: [MGLStyleValue valueWithRawValue:[NSColor yellowColor]],
@20.0: [MGLStyleValue valueWithRawValue:[NSColor blackColor]],
} options:nil];
[self.mapView.style addLayer:theaterLayer];
}
NSURL *imageURL = [NSURL URLWithString:@"https://www.mapbox.com/mapbox-gl-js/assets/radar.gif"];
MGLCoordinateQuad quad = { {46.437, -80.425},
{37.936, -80.425},
{37.936, -71.516},
{46.437, -71.516} };
MGLImageSource *imageSource = [[MGLImageSource alloc] initWithIdentifier:@"radar-source" coordinateQuad:quad URL:imageURL];
[self.mapView.style addSource:imageSource];
MGLRasterStyleLayer * imageLayer = [[MGLRasterStyleLayer alloc] initWithIdentifier:@"radar-layer" source:imageSource];
[self.mapView.style addLayer:imageLayer];
}
- (IBAction)dropPin:(NSMenuItem *)sender {
[self dropPinAtPoint:_mouseLocationForMapViewContextMenu];
}
- (void)dropPinAtPoint:(NSPoint)point {
DroppedPinAnnotation *annotation = [self pinAtPoint:point];
[self.mapView addAnnotation:annotation];
[self.mapView selectAnnotation:annotation];
}
- (DroppedPinAnnotation *)pinAtPoint:(NSPoint)point {
NSArray *features = [self.mapView visibleFeaturesAtPoint:point];
NSString *title;
for (id <MGLFeature> feature in features) {
if (!title) {
title = [feature attributeForKey:@"name_en"] ?: [feature attributeForKey:@"name"];
}
}
DroppedPinAnnotation *annotation = [[DroppedPinAnnotation alloc] init];
annotation.coordinate = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
annotation.title = title ?: @"Dropped Pin";
_spellOutNumberFormatter.numberStyle = NSNumberFormatterSpellOutStyle;
if (_showsToolTipsOnDroppedPins) {
NSString *formattedNumber = [_spellOutNumberFormatter stringFromNumber:@(++_droppedPinCounter)];
annotation.toolTip = formattedNumber;
}
return annotation;
}
- (IBAction)removePin:(NSMenuItem *)sender {
[self removePinAtPoint:_mouseLocationForMapViewContextMenu];
}
- (void)removePinAtPoint:(NSPoint)point {
[self.mapView removeAnnotation:[self.mapView annotationAtPoint:point]];
}
- (IBAction)selectFeatures:(id)sender {
[self selectFeaturesAtPoint:_mouseLocationForMapViewContextMenu];
}
- (void)selectFeaturesAtPoint:(NSPoint)point {
NSArray *features = [self.mapView visibleFeaturesAtPoint:point];
NSArray *flattenedFeatures = MBXFlattenedShapes(features);
[self.mapView addAnnotations:flattenedFeatures];
}
#pragma mark User interface validation
- (BOOL)validateMenuItem:(NSMenuItem *)menuItem {
if (menuItem.action == @selector(showStyle:)) {
NSURL *styleURL = self.mapView.styleURL;
NSCellStateValue state;
switch (menuItem.tag) {
case 1:
state = [styleURL isEqual:[MGLStyle streetsStyleURL]];
break;
case 2:
state = [styleURL isEqual:[MGLStyle outdoorsStyleURL]];
break;
case 3:
state = [styleURL isEqual:[MGLStyle lightStyleURL]];
break;
case 4:
state = [styleURL isEqual:[MGLStyle darkStyleURL]];
break;
case 5:
state = [styleURL isEqual:[MGLStyle satelliteStyleURL]];
break;
case 6:
state = [styleURL isEqual:[MGLStyle satelliteStreetsStyleURL]];
break;
case 7:
state = [styleURL isEqual:[NSURL URLWithString:@"mapbox://styles/mapbox/traffic-day-v2"]];
break;
case 8:
state = [styleURL isEqual:[NSURL URLWithString:@"mapbox://styles/mapbox/traffic-night-v2"]];
break;
default:
return NO;
}
menuItem.state = state;
return YES;
}
if (menuItem.action == @selector(chooseCustomStyle:)) {
menuItem.state = self.indexOfStyleInToolbarItem == NSNotFound;
return YES;
}
if (menuItem.action == @selector(zoomIn:)) {
return self.mapView.zoomLevel < self.mapView.maximumZoomLevel;
}
if (menuItem.action == @selector(zoomOut:)) {
return self.mapView.zoomLevel > self.mapView.minimumZoomLevel;
}
if (menuItem.action == @selector(snapToNorth:)) {
return self.mapView.direction != 0;
}
if (menuItem.action == @selector(reload:)) {
return YES;
}
if (menuItem.action == @selector(toggleLayers:)) {
BOOL isShown = ![self.splitView isSubviewCollapsed:self.splitView.arrangedSubviews.firstObject];
menuItem.title = isShown ? @"Hide Layers" : @"Show Layers";
return YES;
}
if (menuItem.action == @selector(toggleStyleLayers:)) {
NSInteger row = self.styleLayersTableView.clickedRow;
if (row == -1) {
row = self.styleLayersTableView.selectedRow;
}
if (row == -1) {
menuItem.title = @"Show";
} else {
BOOL isVisible = self.mapView.style.reversedLayers[row].visible;
menuItem.title = isVisible ? @"Hide" : @"Show";
}
return row != -1;
}
if (menuItem.action == @selector(deleteStyleLayers:)) {
return self.styleLayersTableView.clickedRow >= 0 || self.styleLayersTableView.selectedRow >= 0;
}
if (menuItem.action == @selector(setLabelLanguage:)) {
menuItem.state = menuItem.tag == _isLocalizingLabels ? NSOnState: NSOffState;
if (menuItem.tag) {
NSLocale *locale = [NSLocale localeWithLocaleIdentifier:[NSBundle mainBundle].developmentLocalization];
NSString *preferredLanguage = [MGLVectorSource preferredMapboxStreetsLanguage];
menuItem.title = [locale displayNameForKey:NSLocaleIdentifier value:preferredLanguage];
}
return YES;
}
if (menuItem.action == @selector(manipulateStyle:)) {
return YES;
}
if (menuItem.action == @selector(dropPin:)) {
id <MGLAnnotation> annotationUnderCursor = [self.mapView annotationAtPoint:_mouseLocationForMapViewContextMenu];
menuItem.hidden = annotationUnderCursor != nil;
return YES;
}
if (menuItem.action == @selector(removePin:)) {
id <MGLAnnotation> annotationUnderCursor = [self.mapView annotationAtPoint:_mouseLocationForMapViewContextMenu];
menuItem.hidden = annotationUnderCursor == nil;
return YES;
}
if (menuItem.action == @selector(selectFeatures:)) {
return YES;
}
if (menuItem.action == @selector(toggleTileBoundaries:)) {
BOOL isShown = self.mapView.debugMask & MGLMapDebugTileBoundariesMask;
menuItem.title = isShown ? @"Hide Tile Boundaries" : @"Show Tile Boundaries";
return YES;
}
if (menuItem.action == @selector(toggleTileInfo:)) {
BOOL isShown = self.mapView.debugMask & MGLMapDebugTileInfoMask;
menuItem.title = isShown ? @"Hide Tile Info" : @"Show Tile Info";
return YES;
}
if (menuItem.action == @selector(toggleTileTimestamps:)) {
BOOL isShown = self.mapView.debugMask & MGLMapDebugTimestampsMask;
menuItem.title = isShown ? @"Hide Tile Timestamps" : @"Show Tile Timestamps";
return YES;
}
if (menuItem.action == @selector(toggleCollisionBoxes:)) {
BOOL isShown = self.mapView.debugMask & MGLMapDebugCollisionBoxesMask;
menuItem.title = isShown ? @"Hide Collision Boxes" : @"Show Collision Boxes";
return YES;
}
if (menuItem.action == @selector(toggleOverdrawVisualization:)) {
BOOL isShown = self.mapView.debugMask & MGLMapDebugOverdrawVisualizationMask;
menuItem.title = isShown ? @"Hide Overdraw Visualization" : @"Show Overdraw Visualization";
return YES;
}
if (menuItem.action == @selector(showColorBuffer:)) {
BOOL enabled = self.mapView.debugMask & (MGLMapDebugStencilBufferMask | MGLMapDebugDepthBufferMask);
menuItem.state = enabled ? NSOffState : NSOnState;
return YES;
}
if (menuItem.action == @selector(showStencilBuffer:)) {
BOOL enabled = self.mapView.debugMask & MGLMapDebugStencilBufferMask;
menuItem.state = enabled ? NSOnState : NSOffState;
return YES;
}
if (menuItem.action == @selector(showDepthBuffer:)) {
BOOL enabled = self.mapView.debugMask & MGLMapDebugDepthBufferMask;
menuItem.state = enabled ? NSOnState : NSOffState;
return YES;
}
if (menuItem.action == @selector(toggleShowsToolTipsOnDroppedPins:)) {
BOOL isShown = _showsToolTipsOnDroppedPins;
menuItem.title = isShown ? @"Hide Tooltips on Dropped Pins" : @"Show Tooltips on Dropped Pins";
return YES;
}
if (menuItem.action == @selector(toggleRandomizesCursorsOnDroppedPins:)) {
BOOL isRandom = _randomizesCursorsOnDroppedPins;
menuItem.title = isRandom ? @"Use Default Cursor for Dropped Pins" : @"Use Random Cursors for Dropped Pins";
return _showsToolTipsOnDroppedPins;
}
if (menuItem.action == @selector(dropManyPins:)) {
return YES;
}
if (menuItem.action == @selector(drawPolygonAndPolyLineAnnotations:)) {
return !_isShowingPolygonAndPolylineAnnotations;
}
if (menuItem.action == @selector(drawAnimatedAnnotation:)) {
return !_isShowingAnimatedAnnotation;
}
if (menuItem.action == @selector(addAnimatedImageSource:)) {
return YES;
}
if (menuItem.action == @selector(insertCustomStyleLayer:)) {
return ![self.mapView.style layerWithIdentifier:@"mbx-custom"];
}
if (menuItem.action == @selector(insertGraticuleLayer:)) {
return ![self.mapView.style sourceWithIdentifier:@"graticule"];
}
if (menuItem.action == @selector(showAllAnnotations:) || menuItem.action == @selector(removeAllAnnotations:)) {
return self.mapView.annotations.count > 0;
}
if (menuItem.action == @selector(startWorldTour:)) {
return !_isTouringWorld;
}
if (menuItem.action == @selector(stopWorldTour:)) {
return _isTouringWorld;
}
if (menuItem.action == @selector(addOfflinePack:)) {
NSURL *styleURL = self.mapView.styleURL;
return !styleURL.isFileURL;
}
if (menuItem.action == @selector(giveFeedback:)) {
return YES;
}
if (menuItem.action == @selector(takeSnapshot:)) {
return !(snapshotter && [snapshotter isLoading]);
}
return NO;
}
- (NSUInteger)indexOfStyleInToolbarItem {
if (![MGLAccountManager accessToken]) {
return NSNotFound;
}
NSArray *styleURLs = @[
[MGLStyle streetsStyleURL],
[MGLStyle outdoorsStyleURL],
[MGLStyle lightStyleURL],
[MGLStyle darkStyleURL],
[MGLStyle satelliteStyleURL],
[MGLStyle satelliteStreetsStyleURL],
[MGLStyle trafficDayStyleURL],
[MGLStyle trafficNightStyleURL],
];
return [styleURLs indexOfObject:self.mapView.styleURL];
}
- (BOOL)validateToolbarItem:(NSToolbarItem *)toolbarItem {
if (!self.mapView) {
return NO;
}
SEL action = toolbarItem.action;
if (action == @selector(showShareMenu:)) {
[(NSButton *)toolbarItem.view sendActionOn:NSLeftMouseDownMask];
if (![MGLAccountManager accessToken]) {
return NO;
}
NSURL *styleURL = self.mapView.styleURL;
return ([styleURL.scheme isEqualToString:@"mapbox"]
&& [styleURL.pathComponents.firstObject isEqualToString:@"styles"]);
}
if (action == @selector(showStyle:)) {
NSPopUpButton *popUpButton = (NSPopUpButton *)toolbarItem.view;
NSUInteger index = self.indexOfStyleInToolbarItem;
if (index == NSNotFound) {
index = -1;
}
[popUpButton selectItemAtIndex:index];
if (index == -1) {
NSString *name = self.mapView.style.name;
popUpButton.title = name ?: @"Custom";
}
}
if (action == @selector(toggleLayers:)) {
BOOL isShown = ![self.splitView isSubviewCollapsed:self.splitView.arrangedSubviews.firstObject];
[(NSButton *)toolbarItem.view setState:isShown ? NSOnState : NSOffState];
}
return NO;
}
#pragma mark NSSharingServicePickerDelegate methods
- (NS_ARRAY_OF(NSSharingService *) *)sharingServicePicker:(NSSharingServicePicker *)sharingServicePicker sharingServicesForItems:(NSArray *)items proposedSharingServices:(NS_ARRAY_OF(NSSharingService *) *)proposedServices {
NSURL *shareURL = self.shareURL;
NSURL *browserURL = [[NSWorkspace sharedWorkspace] URLForApplicationToOpenURL:shareURL];
NSImage *browserIcon = [[NSWorkspace sharedWorkspace] iconForFile:browserURL.path];
NSString *browserName = [[NSFileManager defaultManager] displayNameAtPath:browserURL.path];
NSString *browserServiceName = [NSString stringWithFormat:@"Open in %@", browserName];
NSSharingService *browserService = [[NSSharingService alloc] initWithTitle:browserServiceName
image:browserIcon
alternateImage:nil
handler:^{
[[NSWorkspace sharedWorkspace] openURL:self.shareURL];
}];
NSMutableArray *sharingServices = [proposedServices mutableCopy];
[sharingServices insertObject:browserService atIndex:0];
return sharingServices;
}
#pragma mark NSMenuDelegate methods
- (void)menuWillOpen:(NSMenu *)menu {
if (menu == self.mapViewContextMenu) {
_mouseLocationForMapViewContextMenu = [self.window.contentView convertPoint:self.window.mouseLocationOutsideOfEventStream
toView:self.mapView];
}
}
#pragma mark NSSplitViewDelegate methods
- (BOOL)splitView:(NSSplitView *)splitView canCollapseSubview:(NSView *)subview {
return subview != self.mapView;
}
- (BOOL)splitView:(NSSplitView *)splitView shouldCollapseSubview:(NSView *)subview forDoubleClickOnDividerAtIndex:(NSInteger)dividerIndex {
return YES;
}
#pragma mark MGLMapViewDelegate methods
- (void)mapView:(MGLMapView *)mapView didFinishLoadingStyle:(MGLStyle *)style {
[self updateLabels];
}
- (BOOL)mapView:(MGLMapView *)mapView annotationCanShowCallout:(id <MGLAnnotation>)annotation {
return YES;
}
- (MGLAnnotationImage *)mapView:(MGLMapView *)mapView imageForAnnotation:(id <MGLAnnotation>)annotation {
MGLAnnotationImage *annotationImage = [self.mapView dequeueReusableAnnotationImageWithIdentifier:MGLDroppedPinAnnotationImageIdentifier];
if (!annotationImage) {
NSString *imagePath = [[NSBundle bundleForClass:[MGLMapView class]]
pathForResource:@"default_marker" ofType:@"pdf"];
NSImage *image = [[NSImage alloc] initWithContentsOfFile:imagePath];
NSRect alignmentRect = image.alignmentRect;
alignmentRect.origin.y = NSMidY(alignmentRect);
alignmentRect.size.height /= 2;
image.alignmentRect = alignmentRect;
annotationImage = [MGLAnnotationImage annotationImageWithImage:image
reuseIdentifier:MGLDroppedPinAnnotationImageIdentifier];
}
if (_randomizesCursorsOnDroppedPins) {
NSArray *cursors = @[
[NSCursor IBeamCursor],
[NSCursor crosshairCursor],
[NSCursor pointingHandCursor],
[NSCursor disappearingItemCursor],
[NSCursor IBeamCursorForVerticalLayout],
[NSCursor operationNotAllowedCursor],
[NSCursor dragLinkCursor],
[NSCursor dragCopyCursor],
[NSCursor contextualMenuCursor],
];
annotationImage.cursor = cursors[arc4random_uniform((uint32_t)cursors.count) % cursors.count];
} else {
annotationImage.cursor = nil;
}
return annotationImage;
}
- (void)mapView:(MGLMapView *)mapView didSelectAnnotation:(id <MGLAnnotation>)annotation {
if ([annotation isKindOfClass:[DroppedPinAnnotation class]]) {
DroppedPinAnnotation *droppedPin = (DroppedPinAnnotation *)annotation;
[droppedPin resume];
}
}
- (void)mapView:(MGLMapView *)mapView didDeselectAnnotation:(id <MGLAnnotation>)annotation {
if ([annotation isKindOfClass:[DroppedPinAnnotation class]]) {
DroppedPinAnnotation *droppedPin = (DroppedPinAnnotation *)annotation;
[droppedPin pause];
}
}
- (CGFloat)mapView:(MGLMapView *)mapView alphaForShapeAnnotation:(MGLShape *)annotation {
return 0.8;
}
#pragma mark - MGLComputedShapeSourceDataSource
- (NSArray<id <MGLFeature>>*)featuresInCoordinateBounds:(MGLCoordinateBounds)bounds zoomLevel:(NSUInteger)zoom {
double gridSpacing;
if(zoom >= 13) {
gridSpacing = 0.01;
} else if(zoom >= 11) {
gridSpacing = 0.05;
} else if(zoom == 10) {
gridSpacing = .1;
} else if(zoom == 9) {
gridSpacing = 0.25;
} else if(zoom == 8) {
gridSpacing = 0.5;
} else if (zoom >= 6) {
gridSpacing = 1;
} else if(zoom == 5) {
gridSpacing = 2;
} else if(zoom >= 4) {
gridSpacing = 5;
} else if(zoom == 2) {
gridSpacing = 10;
} else {
gridSpacing = 20;
}
NSMutableArray <id <MGLFeature>> * features = [NSMutableArray array];
CLLocationCoordinate2D coords[2];
for (double y = ceil(bounds.ne.latitude / gridSpacing) * gridSpacing; y >= floor(bounds.sw.latitude / gridSpacing) * gridSpacing; y -= gridSpacing) {
coords[0] = CLLocationCoordinate2DMake(y, bounds.sw.longitude);
coords[1] = CLLocationCoordinate2DMake(y, bounds.ne.longitude);
MGLPolylineFeature *feature = [MGLPolylineFeature polylineWithCoordinates:coords count:2];
feature.attributes = @{@"value": @(y)};
[features addObject:feature];
}
for (double x = floor(bounds.sw.longitude / gridSpacing) * gridSpacing; x <= ceil(bounds.ne.longitude / gridSpacing) * gridSpacing; x += gridSpacing) {
coords[0] = CLLocationCoordinate2DMake(bounds.sw.latitude, x);
coords[1] = CLLocationCoordinate2DMake(bounds.ne.latitude, x);
MGLPolylineFeature *feature = [MGLPolylineFeature polylineWithCoordinates:coords count:2];
feature.attributes = @{@"value": @(x)};
[features addObject:feature];
}
return features;
}
@end
@interface ValidatedToolbarItem : NSToolbarItem
@end
@implementation ValidatedToolbarItem
- (void)validate {
[(MapDocument *)self.toolbar.delegate validateToolbarItem:self];
}
@end
|