Zoom mapview to a region where pins are dropped

后端 未结 3 1550
隐瞒了意图╮
隐瞒了意图╮ 2021-01-16 11:58

If I have 3 pins in a mapview, how will I zoom to these pins, when the map loads. That is, when the map loads I need to have a zoomed view, but the view should accomodate al

3条回答
  •  猫巷女王i
    2021-01-16 12:22

    I wrote the below code in an App and it is similar to @ElanthiraiyanS Answer

    -(void)zoomToFitMapAnnotations:(MKMapView*)mapView insideArray:(NSArray*)anAnnotationArray
    {   
        // NSLog(@"%s", __FUNCTION__);
        if([mapView.annotations count] == 0) return;
    
        CLLocationCoordinate2D topLeftCoord;
        topLeftCoord.latitude = -90;
        topLeftCoord.longitude = 180;
    
    CLLocationCoordinate2D bottomRightCoord;
    bottomRightCoord.latitude = 90;
    bottomRightCoord.longitude = -180;
    
    for(MKPointAnnotation* annotation in anAnnotationArray)
    {
        topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
        topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);
    
        bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
        bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
    }
    
    MKCoordinateRegion region;
    region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
    region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
    region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1; // Add a little extra space on the sides
    region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1; // Add a little extra space on the sides
    
    region = [mapView regionThatFits:region];
    [mapView setRegion:region animated:YES];
    

    }

提交回复
热议问题