Robert
Robert

Reputation: 71

iOS - Displaying all annotations

I am currently working on a piece of functionality using the MapKit. I have ran into a slight problem. Currently I have all my annotations on my map and are displaying when you move the map around.

However, I am trying to get all my pins to be displayed at the same time. I know this isn't possible due to the below link and the limitations of the zoom - my pins can spread across the entire world.

Now I know this is outside of our control but in this scenario the map can sometimes centre between annotations. For example:

Pin in Antartica
Pin in Artic Ocean above Russia.

It will focus the centre of the map roughly on India - 1/2 point between the two pins.

Is there a way of forcing at least one or more pins to be visible if none are visible?

All Annotation is not visible to user in MKMapView

Upvotes: 0

Views: 152

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100543

You can try this to zoom out and show all annotations

func zoomToFitMapAnnotations(aMapView:MKMapView)
{
    if(aMapView.annotations.count == 0)
    {
          return
    }

    var topLeftCoord = CLLocationCoordinate2D.init(latitude: -90, longitude: 180)

    var bottomRightCoord = CLLocationCoordinate2D.init(latitude: 90, longitude: -180)

    for i in 0..<myMapView.annotations.count
    {
        let annotation = myMapView.annotations[i]

        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);
    }

    let resd = CLLocationCoordinate2D.init(latitude: topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5, longitude: topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5)

    let span = MKCoordinateSpan.init(latitudeDelta: fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.3, longitudeDelta: fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.3)       

    var region = MKCoordinateRegion.init(center: resd, span: span);

    region = aMapView.regionThatFits(region)

    aMapView.setRegion(region, animated: true)

}

Upvotes: 0

Related Questions