Remove user location annotation from mapView

2.5k views Asked by At

I have to remove all the annotations added to my MKMapView but when I execute :

NSMutableArray *annotationsToRemove = [[NSMutableArray alloc] initWithArray: mapView.annotations];
[mapView removeAnnotations: annotationsToRemove];

The array annotationsToRemove contains a MKUserLocation annotation and it doesn't delete it.

Is there a way to reset the map? I need to delete all the annotations from it!

3

There are 3 answers

1
Judson Douglas On

You can just set the showsUserLocation property of your mapView to NO.

 mapView.showsUserLocation = NO;
0
Mehul Patel On

Actually you can not edit MKUserLocation annotation. I mean you can not remove it from map annotation's array as it is a read-only property of MKMapView.

If you visit MKMapView.h class. You will find below line

@property (nonatomic, readonly) MKUserLocation *userLocation;

Here we can see that this property is a read only. So we can not delete it from MKMapView annotations array. How ever you face difficulties in calculation with other annotations then you can runtime hide it.

What I am trying to explain is when user location is not required any more you can set NO for user location property.

For example with your code:

NSMutableArray *annotationsToRemove = [[NSMutableArray alloc] initWithArray: mapView.annotations];
[mapView removeAnnotations: annotationsToRemove];

[self.mapView setShowsUserLocation:NO];
NSLog(@"MapView annotations :%@", mapView.annotations);

Check NSLog output, you will see that MKUserLocation annotation is removed from mapView.annotations array.

It is the simple way I did follow. How ever I am not sure about there is other way to do this. Please leave a comment if you found any other solution.

0
dip On

In the h insert

@property (weak)   MKAnnotationView *ulv;

In the m insert

 - (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated {

        MKZoomScale currentZoomScale = mapView.bounds.size.width / mapView.visibleMapRect.size.width;
        NSLog(@"current zoom scale is %f",currentZoomScale);

        ulv = [mapView viewForAnnotation:mapView.userLocation];
                if( currentZoomScale > 0.049 ){
                    ulv.hidden = YES;
                }else{
                    ulv.hidden = NO;
                }

    }