Search code examples
objective-cmkmapviewmkannotation

Add Annotations on mkmapview and set mapview to the region where new annotations are added


I have a MKMapView having many MKAnnotations on it. On a button click, another set of annotations are to be added.

Now on the button click, I have an array of annotations.I add the array of annotations to Mkmapview.

I want the mapview to move to that region where new annotations are added without zoom out or zoom in.

Please help me out with a solution.


Solution

  • I think setting the center to one of the co-ordinates in the array of annotations will serve your purpose

    [_mapView setCenterCoordinate:annotationCoOrd zoomLevel:_zoomLvl animated:YES];
    

    where ,annotationCoOrd is one of the co-ordinates in your array and _zoomLvl is your current zoom-level.

    Would be more helpful if you post your code here.

    for zoom-level

    - (double)getZoomLevel{
    MKCoordinateRegion reg=self.region; // the current visible region
    MKCoordinateSpan span=reg.span; // the deltas
    CLLocationCoordinate2D centerCoordinate=reg.center; // the center in degrees
    // Get the left and right most lonitudes
    CLLocationDegrees leftLongitude=(centerCoordinate.longitude-(span.longitudeDelta/2));
    CLLocationDegrees rightLongitude=(centerCoordinate.longitude+(span.longitudeDelta/2));
    CGSize mapSizeInPixels = self.bounds.size; // the size of the display window
    
    // Get the left and right side of the screen in fully zoomed-in pixels
    double leftPixel=[self longitudeToPixelSpaceX:leftLongitude]; 
    double rightPixel=[self longitudeToPixelSpaceX:rightLongitude];
    // The span of the screen width in fully zoomed-in pixels
    double pixelDelta=abs(rightPixel-leftPixel);
    
    // The ratio of the pixels to what we're actually showing
    double zoomScale= mapSizeInPixels.width /pixelDelta;
    // Inverse exponent
    double zoomExponent=log2(zoomScale);
    // Adjust our scale
    double zoomLevel=zoomExponent+20; 
    return zoomLevel;
    

    }

    - (double)longitudeToPixelSpaceX:(double)longitude
    {
    return round(MERCATOR_OFFSET + MERCATOR_RADIUS * longitude * M_PI / 180.0);
    }
    
    - (double)latitudeToPixelSpaceY:(double)latitude
    {
    return round(MERCATOR_OFFSET - MERCATOR_RADIUS * logf((1 + sinf(latitude * M_PI / 180.0)) / (1 - sinf(latitude * M_PI / 180.0))) / 2.0);
    }
    

    to get the zoom level of the map add the above code in your MKMapView implementation(overriding MKMapview implementation) .