iosmapkitmkuserlocation

Exclude userLocation in MapKit search


I am using MapKit with Xcode 6, and everything I have coded up to this point has worked fine. I have a text field that allows users to input any string to search Apple's map.

However, one of the issues I am having is that when the search results are returned as pins on the map, I would like the zoom to fit ONLY the results, excluding the userLocation icon.

Here is the code I have so far. (I have seen similar code with updates of adding lines to include the userLocation, however the code they say should not contain the userLocation is very similar to what I have already...)

        if (response.mapItems.count == 0)
            NSLog(@"No results");
        else
            for (MKMapItem *item in response.mapItems)
            {


                MKMapRect mr = [self.mapView visibleMapRect];
                MKMapPoint pt = MKMapPointForCoordinate([annotation coordinate]);
                mr.origin.x = pt.x - mr.size.width *0.5; // 0.5
                mr.origin.y = pt.y - mr.size.width * 0.75; //0.75
                [self.mapView setVisibleMapRect:mr animated:YES];

                MKMapRect zoomRect = MKMapRectNull;
                for (id <MKAnnotation> annotation in _mapView.annotations)
                {
                    MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
                    MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 10.4, 10.4);
                    zoomRect = MKMapRectUnion(zoomRect, pointRect);
                }
                [_mapView setVisibleMapRect:zoomRect animated:YES];
            }
    }];
}

Solution

  • Just check to make sure the annotation is not a MKUserLocation object:

    MKMapRect zoomRect = MKMapRectNull;
    for (id <MKAnnotation> annotation in _mapView.annotations) {
        if (![annotation isKindOfClass:[MKUserLocation class]]) {
            MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
            MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 10.4, 10.4);
            zoomRect = MKMapRectUnion(zoomRect, pointRect);
        }
    }
    [_mapView setVisibleMapRect:zoomRect animated:YES];
    

    By the way, I think you want to do this after you finish iterating through the map points, not after each and every one. Though, this means that you should double check to make sure you had one or more map points before doing this.