iOS MKMapView zoom to show all markers

前端 未结 5 838
梦如初夏
梦如初夏 2020-12-02 14:31

I\'m working with MKMapView and have plotted several points on the map. I have used the MKCoordinateRegion and MKCoordinateSpan to ena

5条回答
  •  甜味超标
    2020-12-02 15:11

    Modified Answer with all Perfect Working Code.

    //Zooming the ploted Area
    - (void)zoomToAnnotationsBounds:(NSArray *)latLongArray {
            __block CLLocationDegrees minLatitude = DBL_MAX;
            __block CLLocationDegrees maxLatitude = -DBL_MAX;
            __block CLLocationDegrees minLongitude = DBL_MAX;
            __block CLLocationDegrees maxLongitude = -DBL_MAX;
    
            [latLongArray enumerateObjectsUsingBlock:^(NSString *latLongObj, NSUInteger latLongIdx, BOOL *stop) {
                latLongObj = [latLongArray objectAtIndex:latLongIdx];
                NSArray *latLongPoint = [latLongObj componentsSeparatedByString:@","];
    
                double annotationLat = [[latLongPoint objectAtIndex:0] doubleValue];
                double annotationLong = [[latLongPoint objectAtIndex:1] doubleValue];
                minLatitude = fmin(annotationLat, minLatitude);
                maxLatitude = fmax(annotationLat, maxLatitude);
                minLongitude = fmin(annotationLong, minLongitude);
                maxLongitude = fmax(annotationLong, maxLongitude);
            }];
    
            [self setMapRegionForMinLat:minLatitude minLong:minLongitude maxLat:maxLatitude maxLong:maxLongitude];
    }
    
    
    -(void) setMapRegionForMinLat:(double)minLatitude minLong:(double)minLongitude maxLat:(double)maxLatitude maxLong:(double)maxLongitude {
    
        // pad our map by 10% around the farthest annotations
    
        // we'll make sure that our minimum vertical span is about a kilometer
        // there are ~111km to a degree of latitude. regionThatFits will take care of
        // longitude, which is more complicated, anyway.
    
        MKCoordinateRegion region;
        region.center.latitude = (minLatitude + maxLatitude) / 2;
        region.center.longitude = (minLongitude + maxLongitude) / 2;
    
        region.span.latitudeDelta = (maxLatitude - minLatitude) * MAP_PADDING;
    
        region.span.latitudeDelta = (region.span.latitudeDelta < MINIMUM_VISIBLE_LATITUDE)
        ? MINIMUM_VISIBLE_LATITUDE
        : region.span.latitudeDelta;
    
        region.span.longitudeDelta = (maxLongitude - minLongitude) * MAP_PADDING;
    
        MKCoordinateRegion scaledRegion = [regionsMapView regionThatFits:region];
        [regionsMapView setRegion:scaledRegion animated:YES];
    
    }
    

提交回复
热议问题