2012-09-22 143 views
3

我正在使用地图。我有个问题。我使用以下代码来缩放参考this link in stackOverFlowMKMapView的缩放级别

它很容易缩放地图。
但现在, 我无法放大和缩小地图。这意味着我不能改变或找到另一个地方。它只关注当前位置。它的行为像一个图像修复。我不明白该怎么办? 请帮助。 我的代码如下。

- (void) viewDidLoad 
{ 
[self.mapView.userLocation addObserver:self 
          forKeyPath:@"location" 
           options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) 
           context:nil]; 
} 


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 
{ 
MKCoordinateRegion region; 
region.center = self.mapView.userLocation.coordinate; 

MKCoordinateSpan span; 
span.latitudeDelta = 1; // Change these values to change the zoom 
span.longitudeDelta = 1; 
region.span = span; 

[self.mapView setRegion:region animated:YES]; 
} 
+0

非常相似http://stackoverflow.com/questions/12206646/ios-user-location -keeps-抢购回。此外,您链接的答案是在iOS 4之前,您不再需要KVO来观看用户位置更改。 – Anna

回答

2

我认为问题是,你正在收听的用户位置的变化(这最有可能每秒发生多次),并且您的地图区域设置该区域。

您需要做的是在地图上添加一个按钮(如Apple地图的左上角),这会将地图模式切换为自由模式或固定到用户位置。

当用户按下按钮时,您可以删除/添加KVO。或在代码中切换布尔标志。当该标记为真时,您不会更改地图区域。喜欢的东西:

@implementation YourController{ 
    BOOL _followUserLocation; 
} 

- (IBAction) toggleMapMode:(id)sender{ 
    _followUserLocation = !_followUserLocation; 
} 

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary    *)change context:(void *)context{ 
    if(_followUserLocation){ 
     MKCoordinateRegion region; 
     region.center = self.mapView.userLocation.coordinate; 

     MKCoordinateSpan span; 
     // retain the span so when the map is locked into user location they can still zoom 
     span.latitudeDelta = self.mapView.region.span.latitudeDelta; 
     span.longitudeDelta = self.mapView.region.span.longitudeDelta; 

     region.span = span; 

     [self.mapView setRegion:region animated:YES]; 
    } 
} 

@end 

也许你不想要这一切,你需要的是:

 // retain the span so when the map is locked into user location they can still zoom 
     span.latitudeDelta = self.mapView.region.span.latitudeDelta; 
     span.longitudeDelta = self.mapView.region.span.longitudeDelta; 
+0

它工作正常...非常感谢! – Parthpatel1105