How to create an MKMapRect given two points, each specified with a latitude and longitude value?

This should do it:

// these are your two lat/long coordinates
CLLocationCoordinate2D coordinate1 = CLLocationCoordinate2DMake(lat1,long1);
CLLocationCoordinate2D coordinate2 = CLLocationCoordinate2DMake(lat2,long2);

// convert them to MKMapPoint
MKMapPoint p1 = MKMapPointForCoordinate (coordinate1);
MKMapPoint p2 = MKMapPointForCoordinate (coordinate2);

// and make a MKMapRect using mins and spans
MKMapRect mapRect = MKMapRectMake(fmin(p1.x,p2.x), fmin(p1.y,p2.y), fabs(p1.x-p2.x), fabs(p1.y-p2.y));

this uses the lesser of the two x and y coordinates for your start point, and calculates the x/y spans between the two points for the width and height.


For any number of coordinates, in Swift (4.2):

// Assuming `coordinates` is of type `[CLLocationCoordinate2D]`
let rects = coordinates.lazy.map { MKMapRect(origin: MKMapPoint($0), size: MKMapSize()) }
let fittingRect = rects.reduce(MKMapRect.null) { $0.union($1) }

As noted by @Abin Baby, this will not take wrap around into account (at +/-180 longitude & +/-90 latitude). The result will still be correct, but it will not be the smallest possible rectangle.


Based on Patrick's answer an extension on MKMapRect:

extension MKMapRect {
    init(coordinates: [CLLocationCoordinate2D]) {
        self = coordinates.map({ MKMapPointForCoordinate($0) }).map({ MKMapRect(origin: $0, size: MKMapSize(width: 0, height: 0)) }).reduce(MKMapRectNull, combine: MKMapRectUnion)
    }
}

Tags:

Ios

Mapkit