Reputation: 349
I am working with map. I have a problem. I used following code to Zoom from the reference of this link in stackOverFlow
It's Easy to Zoom map.
But now,
I can't zoom in and out map. it means i cant change or find another place. it's only focus on current location. It's behave like an image Fix are. I can't understand what to do?
Please Help.
My Code as Follow.
- (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];
}
Upvotes: 3
Views: 1355
Reputation: 410
I think the problem is that you are listening to user location changes (which most probably happening multiple times per second) and you are setting the map region to that region.
What you need to do is add a button on the map (like top left corner in Apple maps) which will toggle the map-mode to either free look or fixed to user location.
When the user press the button, you either remove/add the KVO. or toggle a boolean flag in your code. When the flag is true, you don't change map region. Something like:
@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
Maybe you don't want all this and all you need is:
// 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;
Upvotes: 2