RMMapContents.m
27.6 KB
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
//
// RMMapContents.m
//
// Copyright (c) 2008, Route-Me Contributors
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#import "RMMapContents.h"
#import "RMMapView.h"
#import "RMFoundation.h"
#import "RMProjection.h"
#import "RMMercatorToScreenProjection.h"
#import "RMMercatorToTileProjection.h"
#import "RMTileSource.h"
#import "RMTileLoader.h"
#import "RMTileImageSet.h"
#import "RMOpenStreetMapsSource.h"
#import "RMCoreAnimationRenderer.h"
#import "RMCachedTileSource.h"
#import "RMLayerSet.h"
#import "RMMarkerManager.h"
#import "RMMarker.h"
@interface RMMapContents (PrivateMethods)
- (void)animatedZoomStep:(NSTimer *)timer;
@end
@implementation RMMapContents (Internal)
BOOL delegateHasRegionUpdate;
@end
@implementation RMMapContents
@synthesize boundingMask;
@synthesize minZoom;
@synthesize maxZoom;
@synthesize markerManager;
#pragma mark Initialisation
- (id)initWithView: (UIView*) view
{
LogMethod();
CLLocationCoordinate2D here;
here.latitude = kDefaultInitialLatitude;
here.longitude = kDefaultInitialLongitude;
return [self initWithView:view
tilesource:[[RMOpenStreetMapsSource alloc] init]
centerLatLon:here
zoomLevel:kDefaultInitialZoomLevel
maxZoomLevel:kDefaultMaximumZoomLevel
minZoomLevel:kDefaultMinimumZoomLevel
backgroundImage:nil];
}
- (id)initWithView: (UIView*) view
tilesource:(id<RMTileSource>)newTilesource
{
LogMethod();
CLLocationCoordinate2D here;
here.latitude = kDefaultInitialLatitude;
here.longitude = kDefaultInitialLongitude;
return [self initWithView:view
tilesource:newTilesource
centerLatLon:here
zoomLevel:kDefaultInitialZoomLevel
maxZoomLevel:kDefaultMaximumZoomLevel
minZoomLevel:kDefaultMinimumZoomLevel
backgroundImage:nil];
}
- (id)initWithView:(UIView*)newView
tilesource:(id<RMTileSource>)newTilesource
centerLatLon:(CLLocationCoordinate2D)initialCenter
zoomLevel:(float)initialZoomLevel
maxZoomLevel:(float)maxZoomLevel
minZoomLevel:(float)minZoomLevel
backgroundImage:(UIImage *)backgroundImage
{
LogMethod();
if (![super init])
return nil;
NSAssert1([newView isKindOfClass:[RMMapView class]], @"view %@ must be a subclass of RMMapView", newView);
[(RMMapView *)newView setContents:self];
renderer = [[RMCoreAnimationRenderer alloc] initWithContent:self];
boundingMask = RMMapMinWidthBound;
mercatorToScreenProjection = [[RMMercatorToScreenProjection alloc] initFromProjection:[newTilesource projection] ToScreenBounds:[newView bounds]];
tileSource = nil;
projection = nil;
mercatorToTileProjection = nil;
renderer = nil;
imagesOnScreen = nil;
tileLoader = nil;
layer = [[newView layer] retain];
[self setTileSource:newTilesource];
[self setRenderer: [[[RMCoreAnimationRenderer alloc] initWithContent:self] autorelease]];
imagesOnScreen = [[RMTileImageSet alloc] initWithDelegate:renderer];
[imagesOnScreen setTileSource:tileSource];
tileLoader = [[RMTileLoader alloc] initWithContent:self];
[tileLoader setSuppressLoading:YES];
minZoom = minZoomLevel;
maxZoom = maxZoomLevel;
NSAssert((minZoom < initialZoomLevel), @"initial zoom level must be greater than minimum zoom level");
NSAssert((maxZoom > initialZoomLevel), @"initial zoom level must be less than maximum zoom level");
[self setZoom:initialZoomLevel];
[self moveToLatLong:initialCenter];
[tileLoader setSuppressLoading:NO];
// TODO: Make a nice background class
RMMapLayer *theBackground = [[RMMapLayer alloc] init];
[self setBackground:theBackground];
[theBackground release];
RMLayerSet *theOverlay = [[RMLayerSet alloc] initForContents:self];
[self setOverlay:theOverlay];
[theOverlay release];
markerManager = [[RMMarkerManager alloc] initWithContents:self];
[newView setNeedsDisplay];
RMLog(@"Map contents initialised. view: %@ tileSource %@ renderer %@", newView, tileSource, renderer);
return self;
}
/// deprecated at any moment after release 0.5
- (id) initForView: (UIView*) view
{
return [self initWithView:view];
}
/// deprecated at any moment after release 0.5
- (id) initForView: (UIView*) view WithLocation:(CLLocationCoordinate2D)latlong
{
LogMethod();
id<RMTileSource> _tileSource = [[RMOpenStreetMapsSource alloc] init];
RMMapRenderer *_renderer = [[RMCoreAnimationRenderer alloc] initWithContent:self];
id mapContents = [self initForView:view WithTileSource:_tileSource WithRenderer:_renderer LookingAt:latlong];
[_tileSource release];
[_renderer release];
return mapContents;
}
/// deprecated at any moment after release 0.5
- (id) initForView: (UIView*) view WithTileSource: (id<RMTileSource>)_tileSource WithRenderer: (RMMapRenderer*)_renderer LookingAt:(CLLocationCoordinate2D)latlong
{
LogMethod();
if (![super init])
return nil;
NSAssert1([view isKindOfClass:[RMMapView class]], @"view %@ must be a subclass of RMMapView", view);
[self setMaxZoom:kDefaultMaximumZoomLevel];
self.boundingMask = RMMapMinWidthBound;
// targetView = view;
mercatorToScreenProjection = [[RMMercatorToScreenProjection alloc] initFromProjection:[_tileSource projection] ToScreenBounds:[view bounds]];
tileSource = nil;
projection = nil;
mercatorToTileProjection = nil;
renderer = nil;
imagesOnScreen = nil;
tileLoader = nil;
layer = [[view layer] retain];
[self setTileSource:_tileSource];
[self setRenderer:_renderer];
imagesOnScreen = [[RMTileImageSet alloc] initWithDelegate:renderer];
[imagesOnScreen setTileSource:tileSource];
tileLoader = [[RMTileLoader alloc] initWithContent:self];
[tileLoader setSuppressLoading:YES];
[self setZoom:kDefaultInitialZoomLevel];
[self moveToLatLong:latlong];
[tileLoader setSuppressLoading:NO];
// TODO: Make a nice background class
RMMapLayer *theBackground = [[RMMapLayer alloc] init];
[self setBackground:theBackground];
[theBackground release];
RMLayerSet *theOverlay = [[RMLayerSet alloc] initForContents:self];
[self setOverlay:theOverlay];
[theOverlay release];
markerManager = [[RMMarkerManager alloc] initWithContents:self];
[view setNeedsDisplay];
RMLog(@"Map contents initialised. view: %@ tileSource %@ renderer %@", view, tileSource, renderer);
return self;
}
- (void)setFrame:(CGRect)frame
{
CGRect bounds = CGRectMake(0, 0, frame.size.width, frame.size.height);
[mercatorToScreenProjection setScreenBounds:bounds];
background.frame = bounds;
layer.frame = frame;
overlay.frame = bounds;
[tileLoader clearLoadedBounds];
[tileLoader updateLoadedImages];
[renderer setFrame:frame];
[overlay correctPositionOfAllSublayers];
}
-(void) dealloc
{
LogMethod();
[imagesOnScreen cancelLoading];
[self setRenderer:nil];
[imagesOnScreen release];
[tileLoader release];
[projection release];
[mercatorToTileProjection release];
[mercatorToScreenProjection release];
[tileSource release];
[self setOverlay:nil];
[self setBackground:nil];
[layer release];
[markerManager release];
RMLog(@"mapcontents dealloced");
[super dealloc];
}
- (void) didReceiveMemoryWarning
{
LogMethod();
[tileSource didReceiveMemoryWarning];
}
#pragma mark Forwarded Events
- (void)moveToLatLong: (CLLocationCoordinate2D)latlong
{
RMXYPoint aPoint = [projection latLongToPoint:latlong];
[self moveToXYPoint: aPoint];
}
- (void)moveToXYPoint: (RMXYPoint)aPoint
{
[mercatorToScreenProjection setXYCenter:aPoint];
[overlay correctPositionOfAllSublayers];
[tileLoader reload];
[renderer setNeedsDisplay];
}
- (void)moveBy: (CGSize) delta
{
[mercatorToScreenProjection moveScreenBy:delta];
[imagesOnScreen moveBy:delta];
[tileLoader moveBy:delta];
[overlay moveBy:delta];
[overlay correctPositionOfAllSublayers];
[renderer setNeedsDisplay];
}
- (float)adjustZoomForBoundingMask:(float)zoomFactor
{
if ( boundingMask == RMMapNoMinBound )
return zoomFactor;
double newScale = self.scale / zoomFactor;
RMXYRect mercatorBounds = [[tileSource projection] bounds];
// Check for MinWidthBound
if ( boundingMask & RMMapMinWidthBound )
{
double newMapContentsWidth = mercatorBounds.size.width / newScale;
double screenBoundsWidth = [self screenBounds].size.width;
double mapContentWidth;
if ( newMapContentsWidth < screenBoundsWidth )
{
// Calculate new zoom facter so that it does not shrink the map any further.
mapContentWidth = mercatorBounds.size.width / self.scale;
zoomFactor = screenBoundsWidth / mapContentWidth;
newScale = self.scale / zoomFactor;
newMapContentsWidth = mercatorBounds.size.width / newScale;
}
}
// Check for MinHeightBound
if ( boundingMask & RMMapMinHeightBound )
{
double newMapContentsHeight = mercatorBounds.size.height / newScale;
double screenBoundsHeight = [self screenBounds].size.height;
double mapContentHeight;
if ( newMapContentsHeight < screenBoundsHeight )
{
// Calculate new zoom facter so that it does not shrink the map any further.
mapContentHeight = mercatorBounds.size.height / self.scale;
zoomFactor = screenBoundsHeight / mapContentHeight;
newScale = self.scale / zoomFactor;
newMapContentsHeight = mercatorBounds.size.height / newScale;
}
}
//[self adjustMapPlacementWithScale:newScale];
return zoomFactor;
}
// This currently is not called because it does not handle the case when the map is continous or not continous. At a certain scale
// you can continuously move to the west or east until you get to a certain scale level that simply shows the entire world.
- (void)adjustMapPlacementWithScale:(float)aScale
{
CGSize adjustmentDelta = {0.0, 0.0};
RMLatLong rightEdgeLatLong = {0, 180};
RMLatLong leftEdgeLatLong = {0,- 180};
CGPoint rightEdge = [self latLongToPixel:rightEdgeLatLong withScale:aScale];
CGPoint leftEdge = [self latLongToPixel:leftEdgeLatLong withScale:aScale];
//CGPoint topEdge = [self latLongToPixel:myLatLong withScale:aScale];
//CGPoint bottomEdge = [self latLongToPixel:myLatLong withScale:aScale];
CGRect containerBounds = [self screenBounds];
if ( rightEdge.x < containerBounds.size.width )
{
adjustmentDelta.width = containerBounds.size.width - rightEdge.x;
[self moveBy:adjustmentDelta];
}
if ( leftEdge.x > containerBounds.origin.x )
{
adjustmentDelta.width = containerBounds.origin.x - leftEdge.x;
[self moveBy:adjustmentDelta];
}
}
- (void)setZoomBounds:(float)aMinZoom maxZoom:(float)aMaxZoom
{
[self setMinZoom: aMinZoom];
[self setMaxZoom: aMaxZoom];
}
- (void)zoomByFactor: (float) zoomFactor near:(CGPoint) pivot
{
//[self zoomByFactor:zoomFactor near:pivot animated:NO];
zoomFactor = [self adjustZoomForBoundingMask:zoomFactor];
//RMLog(@"Zoom Factor: %lf for Zoom:%f", zoomFactor, [self zoom]);
// pre-calculate zoom so we can tell if we want to perform it
float newZoom = [mercatorToTileProjection
calculateZoomFromScale:self.scale/zoomFactor];
if ((newZoom > minZoom) && (newZoom < maxZoom))
{
[mercatorToScreenProjection zoomScreenByFactor:zoomFactor near:pivot];
[imagesOnScreen zoomByFactor:zoomFactor near:pivot];
[tileLoader zoomByFactor:zoomFactor near:pivot];
[overlay zoomByFactor:zoomFactor near:pivot];
[renderer setNeedsDisplay];
}
}
- (void)zoomByFactor: (float) zoomFactor near:(CGPoint) pivot animated:(BOOL) animated
{
[self zoomByFactor:zoomFactor near:pivot animated:animated withCallback:nil];
}
- (void)zoomByFactor: (float) zoomFactor near:(CGPoint) pivot animated:(BOOL) animated withCallback:(id<RMMapContentsAnimationCallback>)callback
{
zoomFactor = [self adjustZoomForBoundingMask:zoomFactor];
if (animated)
{
float zoomDelta = log2f(zoomFactor);
float targetZoom = zoomDelta + [self zoom];
// goal is to complete the animation in animTime seconds
static const float stepTime = 0.03f;
static const float animTime = 0.1f;
float nSteps = animTime / stepTime;
float zoomIncr = zoomDelta / nSteps;
CFDictionaryRef pivotDictionary = CGPointCreateDictionaryRepresentation(pivot);
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:zoomIncr], @"zoomIncr",
[NSNumber numberWithFloat:targetZoom], @"targetZoom",
pivotDictionary, @"pivot",
callback, @"callback", nil];
CFRelease(pivotDictionary);
[NSTimer scheduledTimerWithTimeInterval:stepTime
target:self
selector:@selector(animatedZoomStep:)
userInfo:userInfo
repeats:YES];
}
else
{
//bools for syntactical sugar to understand the logic in the if statement below
BOOL zoomAtMax = ([self zoom] == [self maxZoom]);
BOOL zoomAtMin = ([self zoom] == [self minZoom]);
BOOL zoomGreaterMin = ([self zoom] > [self minZoom]);
BOOL zoomLessMax = ([self zoom] < [self maxZoom]);
//zooming in zoomFactor > 1
//zooming out zoomFactor < 1
if ((zoomGreaterMin && zoomLessMax) || (zoomAtMax && zoomFactor<1) || (zoomAtMin && zoomFactor>1))
{
[mercatorToScreenProjection zoomScreenByFactor:zoomFactor near:pivot];
[imagesOnScreen zoomByFactor:zoomFactor near:pivot];
[tileLoader zoomByFactor:zoomFactor near:pivot];
[overlay zoomByFactor:zoomFactor near:pivot];
[renderer setNeedsDisplay];
}
else
{
if([self zoom] > [self maxZoom])
[self setZoom:[self maxZoom]];
if([self zoom] < [self minZoom])
[self setZoom:[self minZoom]];
}
}
}
- (void)animatedZoomStep:(NSTimer *)timer
{
float zoomIncr = [[[timer userInfo] objectForKey:@"zoomIncr"] floatValue];
float targetZoom = [[[timer userInfo] objectForKey:@"targetZoom"] floatValue];
if ((zoomIncr > 0 && [self zoom] >= targetZoom) || (zoomIncr < 0 && [self zoom] <= targetZoom))
{
NSDictionary * userInfo = [[timer userInfo] retain];
[timer invalidate]; // ASAP
id<RMMapContentsAnimationCallback> callback = [userInfo objectForKey:@"callback"];
if (callback && [callback respondsToSelector:@selector(animationFinishedWithZoomFactor:near:)]) {
CGPoint pivot;
CGPointMakeWithDictionaryRepresentation((CFDictionaryRef)[userInfo objectForKey:@"pivot"], &pivot);
[callback animationFinishedWithZoomFactor:targetZoom near:pivot];
}
[userInfo release];
}
else
{
float zoomFactorStep = exp2f(zoomIncr);
CGPoint pivot;
CGPointMakeWithDictionaryRepresentation((CFDictionaryRef)[[timer userInfo] objectForKey:@"pivot"], &pivot);
[self zoomByFactor:zoomFactorStep near:pivot animated:NO];
}
}
- (void)zoomInToNextNativeZoomAt:(CGPoint) pivot
{
[self zoomInToNextNativeZoomAt:pivot animated:NO];
}
- (float)getNextNativeZoomFactor
{
float newZoom = roundf([self zoom] + 1);
return newZoom >= [self maxZoom] ? 0 : exp2f(newZoom - [self zoom]);
}
- (void)zoomInToNextNativeZoomAt:(CGPoint) pivot animated:(BOOL) animated
{
// Calculate rounded zoom
float newZoom = roundf([self zoom] + 1);
if (newZoom >= [self maxZoom])
return;
else
{
float factor = exp2f(newZoom - [self zoom]);
[self zoomByFactor:factor near:pivot animated:animated];
}
}
- (void)zoomOutToNextNativeZoomAt:(CGPoint) pivot animated:(BOOL) animated {
// Calculate rounded zoom
float newZoom = roundf([self zoom] - 1);
if (newZoom <= [self minZoom])
return;
else {
float factor = exp2f(newZoom - [self zoom]);
[self zoomByFactor:factor near:pivot animated:animated];
}
}
- (void)zoomOutToNextNativeZoomAt:(CGPoint) pivot {
[self zoomOutToNextNativeZoomAt: pivot animated: FALSE];
}
- (void) drawRect: (CGRect) aRect
{
[renderer drawRect:aRect];
}
#pragma mark Properties
- (void) setTileSource: (id<RMTileSource>)newTileSource
{
if (tileSource == newTileSource)
return;
newTileSource = [RMCachedTileSource cachedTileSourceWithSource:newTileSource];
[tileSource release];
tileSource = [newTileSource retain];
[projection release];
projection = [[tileSource projection] retain];
[mercatorToTileProjection release];
mercatorToTileProjection = [[tileSource mercatorToTileProjection] retain];
// TODO: Fix the min / max zoom.
// [self setMinZoom:[newTileSource minZoom]];
// [self setMaxZoom:[newTileSource maxZoom]];
[imagesOnScreen setTileSource:tileSource];
[tileLoader reload];
}
- (id<RMTileSource>) tileSource
{
return [[tileSource retain] autorelease];
}
- (void) setRenderer: (RMMapRenderer*) newRenderer
{
if (renderer == newRenderer)
return;
[imagesOnScreen setDelegate:newRenderer];
[[renderer layer] removeFromSuperlayer];
[renderer release];
renderer = [newRenderer retain];
if (renderer == nil)
return;
// CGRect rect = [self screenBounds];
// RMLog(@"%f %f %f %f", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
[[renderer layer] setFrame:[self screenBounds]];
if (background != nil)
[layer insertSublayer:[renderer layer] above:background];
else if (overlay != nil)
[layer insertSublayer:[renderer layer] below:overlay];
else
[layer insertSublayer:[renderer layer] atIndex: 0];
}
- (RMMapRenderer *)renderer
{
return [[renderer retain] autorelease];
}
- (void) setBackground: (RMMapLayer*) aLayer
{
if (background == aLayer) return;
if (background != nil)
{
[background release];
[background removeFromSuperlayer];
}
background = [aLayer retain];
if (background == nil)
return;
background.frame = [self screenBounds];
if ([renderer layer] != nil)
[layer insertSublayer:background below:[renderer layer]];
else if (overlay != nil)
[layer insertSublayer:background below:overlay];
else
[layer insertSublayer:[renderer layer] atIndex: 0];
}
- (RMMapLayer *)background
{
return [[background retain] autorelease];
}
- (void) setOverlay: (RMLayerSet*) aLayer
{
if (overlay == aLayer) return;
if (overlay != nil)
{
[overlay release];
[overlay removeFromSuperlayer];
}
overlay = [aLayer retain];
if (overlay == nil)
return;
overlay.frame = [self screenBounds];
if ([renderer layer] != nil)
[layer insertSublayer:overlay above:[renderer layer]];
else if (background != nil)
[layer insertSublayer:overlay above:background];
else
[layer insertSublayer:[renderer layer] atIndex: 0];
/* Test to make sure the overlay is working.
CALayer *testLayer = [[CALayer alloc] init];
[testLayer setFrame:CGRectMake(100, 100, 200, 200)];
[testLayer setBackgroundColor:[[UIColor brownColor] CGColor]];
RMLog(@"added test layer");
[overlay addSublayer:testLayer];*/
}
- (RMLayerSet *)overlay
{
return [[overlay retain] autorelease];
}
- (CLLocationCoordinate2D) mapCenter
{
RMXYPoint aPoint = [mercatorToScreenProjection XYCenter];
return [projection pointToLatLong:aPoint];
}
-(void) setMapCenter: (CLLocationCoordinate2D) center
{
[self moveToLatLong:center];
}
-(RMXYRect) XYBounds
{
return [mercatorToScreenProjection XYBounds];
}
-(void) setXYBounds: (RMXYRect) boundsRect
{
[mercatorToScreenProjection setXYBounds:boundsRect];
}
-(RMTileRect) tileBounds
{
return [mercatorToTileProjection project: mercatorToScreenProjection];
}
-(CGRect) screenBounds
{
if (mercatorToScreenProjection != nil)
return [mercatorToScreenProjection screenBounds];
else
return CGRectMake(0, 0, 0, 0);
}
-(float) scale
{
return [mercatorToScreenProjection scale];
}
-(void) setScale: (float) scale
{
[mercatorToScreenProjection setScale:scale];
[overlay correctPositionOfAllSublayers];
[tileLoader updateLoadedImages];
[renderer setNeedsDisplay];
}
-(float) zoom
{
return [mercatorToTileProjection calculateZoomFromScale:[mercatorToScreenProjection scale]];
}
/*-(void) setZoom: (float) zoom
{
//limit the zoom to maxZoom and minZoom as specified by projection - why do we also store maxZoom?
float normalisedZoom = [mercatorToTileProjection normaliseZoom:zoom];
float scale = [mercatorToTileProjection calculateScaleFromZoom:normalisedZoom];
[self setScale:scale];
}
*/
-(void) setZoom: (float) zoom
{
//RMLog(@"set zoom: %f", zoom);
if (zoom > maxZoom)
return;
float scale = [mercatorToTileProjection
calculateScaleFromZoom:zoom];
//RMLog(@"new scale: %f, scale");
[self setScale:scale];
[overlay correctPositionOfAllSublayers];
}
-(RMTileImageSet*) imagesOnScreen
{
return [[imagesOnScreen retain] autorelease];
}
-(RMTileLoader*) tileLoader
{
return [[tileLoader retain] autorelease];
}
-(RMProjection*) projection
{
return [[projection retain] autorelease];
}
-(id<RMMercatorToTileProjection>) mercatorToTileProjection
{
return [[mercatorToTileProjection retain] autorelease];
}
-(RMMercatorToScreenProjection*) mercatorToScreenProjection
{
return [[mercatorToScreenProjection retain] autorelease];
}
- (CALayer *)layer
{
return [[layer retain] autorelease];
}
static BOOL _performExpensiveOperations = YES;
+ (BOOL) performExpensiveOperations
{
return _performExpensiveOperations;
}
+ (void) setPerformExpensiveOperations: (BOOL)p
{
if (p == _performExpensiveOperations)
return;
_performExpensiveOperations = p;
if (p)
[[NSNotificationCenter defaultCenter] postNotificationName:RMResumeExpensiveOperations object:self];
else
[[NSNotificationCenter defaultCenter] postNotificationName:RMSuspendExpensiveOperations object:self];
}
#pragma mark LatLng/Pixel translation functions
- (CGPoint)latLongToPixel:(CLLocationCoordinate2D)latlong
{
return [mercatorToScreenProjection projectXYPoint:[projection latLongToPoint:latlong]];
}
- (CGPoint)latLongToPixel:(CLLocationCoordinate2D)latlong withScale:(float)aScale
{
return [mercatorToScreenProjection projectXYPoint:[projection latLongToPoint:latlong] withScale:aScale];
}
- (RMTilePoint)latLongToTilePoint:(CLLocationCoordinate2D)latlong withScale:(float)aScale
{
return [mercatorToTileProjection project:[projection latLongToPoint:latlong] atZoom:aScale];
}
- (CLLocationCoordinate2D)pixelToLatLong:(CGPoint)aPixel
{
return [projection pointToLatLong:[mercatorToScreenProjection projectScreenPointToXY:aPixel]];
}
- (CLLocationCoordinate2D)pixelToLatLong:(CGPoint)aPixel withScale:(float)aScale
{
return [projection pointToLatLong:[mercatorToScreenProjection projectScreenPointToXY:aPixel withScale:aScale]];
}
- (double)trueScaleDenominator {
double routemeMetersPerPixel = [self scale]; // really meters/pixel
double iphoneMillimetersPerPixel = .1543;
double truescaleDenominator = routemeMetersPerPixel / (0.001 * iphoneMillimetersPerPixel) ;
return truescaleDenominator;
}
#pragma mark Zoom With Bounds
- (void)zoomWithLatLngBoundsNorthEast:(CLLocationCoordinate2D)ne SouthWest:(CLLocationCoordinate2D)sw
{
if(ne.latitude == sw.latitude && ne.longitude == sw.longitude)//There are no bounds, probably only one marker.
{
RMXYRect zoomRect;
RMXYPoint myOrigin = [projection latLongToPoint:sw];
//Default is with scale = 2.0 mercators/pixel
zoomRect.size.width = [self screenBounds].size.width * 2.0;
zoomRect.size.height = [self screenBounds].size.height * 2.0;
myOrigin.x = myOrigin.x - (zoomRect.size.width / 2);
myOrigin.y = myOrigin.y - (zoomRect.size.height / 2);
zoomRect.origin = myOrigin;
[self zoomWithRMMercatorRectBounds:zoomRect];
}
else
{
//convert ne/sw into RMMercatorRect and call zoomWithBounds
float pixelBuffer = 50;
CLLocationCoordinate2D midpoint = {
.latitude = (ne.latitude + sw.latitude) / 2,
.longitude = (ne.longitude + sw.longitude) / 2
};
RMXYPoint myOrigin = [projection latLongToPoint:midpoint];
RMXYPoint nePoint = [projection latLongToPoint:ne];
RMXYPoint swPoint = [projection latLongToPoint:sw];
RMXYPoint myPoint = {.x = nePoint.x - swPoint.x, .y = nePoint.y - swPoint.y};
//Create the new zoom layout
RMXYRect zoomRect;
//Default is with scale = 2.0 mercators/pixel
zoomRect.size.width = [self screenBounds].size.width * 2.0;
zoomRect.size.height = [self screenBounds].size.height * 2.0;
if((myPoint.x / ([self screenBounds].size.width)) < (myPoint.y / ([self screenBounds].size.height)))
{
if((myPoint.y / ([self screenBounds].size.height - pixelBuffer)) > 1)
{
zoomRect.size.width = [self screenBounds].size.width * (myPoint.y / ([self screenBounds].size.height - pixelBuffer));
zoomRect.size.height = [self screenBounds].size.height * (myPoint.y / ([self screenBounds].size.height - pixelBuffer));
}
}
else
{
if((myPoint.x / ([self screenBounds].size.width - pixelBuffer)) > 1)
{
zoomRect.size.width = [self screenBounds].size.width * (myPoint.x / ([self screenBounds].size.width - pixelBuffer));
zoomRect.size.height = [self screenBounds].size.height * (myPoint.x / ([self screenBounds].size.width - pixelBuffer));
}
}
myOrigin.x = myOrigin.x - (zoomRect.size.width / 2);
myOrigin.y = myOrigin.y - (zoomRect.size.height / 2);
RMLog(@"Origin is calculated at: %f, %f", [projection pointToLatLong:myOrigin].latitude, [projection pointToLatLong:myOrigin].longitude);
/*It gets all messed up if our origin is lower than the lowest place on the map, so we check.
if(myOrigin.y < -19971868.880409)
{
myOrigin.y = -19971868.880409;
}*/
zoomRect.origin = myOrigin;
[self zoomWithRMMercatorRectBounds:zoomRect];
}
}
- (void)zoomWithRMMercatorRectBounds:(RMXYRect)bounds
{
[self setXYBounds:bounds];
[overlay correctPositionOfAllSublayers];
[tileLoader clearLoadedBounds];
[tileLoader updateLoadedImages];
[renderer setNeedsDisplay];
}
#pragma mark Markers and overlays
// Move overlays stuff here - at the moment overlay stuff is above...
- (RMLatLongBounds) getScreenCoordinateBounds
{
CGRect rect = [mercatorToScreenProjection screenBounds];
return [self getCoordinateBounds:rect];
}
- (RMLatLongBounds) getCoordinateBounds:(CGRect) rect
{
RMLatLongBounds bounds;
CGPoint northWest = rect.origin;
CGPoint southEast;
southEast.x = rect.origin.x + rect.size.width;
southEast.y = rect.origin.y + rect.size.height;
// RMLog(@"NortWest x:%lf y:%lf", northWest.x, northWest.y);
// RMLog(@"SouthEast x:%lf y:%lf", southEast.x, southEast.y);
bounds.northWest = [self pixelToLatLong:northWest];
bounds.southEast = [self pixelToLatLong:southEast];
// RMLog(@"NortWest Lat:%lf Lon:%lf", bounds.northWest.latitude, bounds.northWest.longitude);
// RMLog(@"SouthEast Lat:%lf Lon:%lf", bounds.southEast.latitude, bounds.southEast.longitude);
return bounds;
}
- (void) tilesUpdatedRegion:(CGRect)region
{
if(delegateHasRegionUpdate)
{
RMLatLongBounds locationBounds = [self getCoordinateBounds:region];
[tilesUpdateDelegate regionUpdate:locationBounds];
}
}
- (void) printDebuggingInformation
{
[imagesOnScreen printDebuggingInformation];
}
@dynamic tilesUpdateDelegate;
- (void) setTilesUpdateDelegate: (id<RMTilesUpdateDelegate>) _tilesUpdateDelegate
{
if (tilesUpdateDelegate == _tilesUpdateDelegate) return;
tilesUpdateDelegate= _tilesUpdateDelegate;
//RMLog(@"Delegate type:%@",[(NSObject *) tilesUpdateDelegate description]);
delegateHasRegionUpdate = [(NSObject*) tilesUpdateDelegate respondsToSelector: @selector(regionUpdate:)];
}
- (id<RMTilesUpdateDelegate>) tilesUpdateDelegate
{
return tilesUpdateDelegate;
}
@end