iosswiftmapkitmkcoordinateregion

How to create a bounding box for a geolocation


I want to create a bounding box for a geolocation in Swift which returns to me (minY maxY minX maxX) Is there a function to do this in Swift?


Solution

  • iOS doesn't have the idea of a bounding box, but it does have a region struct called MKCoordinateRegion.

    MKCoordinateRegion contains two things:

    CLLocationCoordinate2D center;
    MKCoordinateSpan span;
    

    Both are structs. The span contains the height and width of the region. Using those you can make a bounding box (from here)

    CLLocationCoordinate2D centerCoord = CLLocationCoordinate2DMake(41.145495, −73.994901);
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(centerCoord, 2000, 2000);
    
    double latMin = region.center.latitude - .5 * startRegion.span.latitudeDelta;
    double latMax = region.center.latitude + .5 * startRegion.span.latitudeDelta;
    double lonMin = region.center.longitude - .5 * startRegion.span.longitudeDelta;
    double lonMax = region.center.longitude + .5 * startRegion.span.longitudeDelta;
    

    Edit: I just realised the request was for Swift. I'll leave translation as an exercise for bonus points.