Skip to content

Instantly share code, notes, and snippets.

@audiocommander
Forked from aaronpk/gist:6693579
Last active October 26, 2023 13:48
Show Gist options
  • Save audiocommander/6c70f5acf8de2daba2c03c429370ca69 to your computer and use it in GitHub Desktop.
Save audiocommander/6c70f5acf8de2daba2c03c429370ca69 to your computer and use it in GitHub Desktop.
Center a MKMapView given a GeoJSON bounding box
// prepare bbox
struct BoundingBox {
// latitudes range from -90 .. +90
// longitudes range from -180 .. +180
var latmin = 90.0
var latmax = -90.0
var lngmin = 180.0
var lngmax = -180.0
}
var bbox = BoundingBox()
/*
// get the bounding box
if lat < bbox.latmin { bbox.latmin = lat }
if lat > bbox.latmax { bbox.latmax = lat }
if lng < bbox.lngmin { bbox.lngmin = lng }
if lng > bbox.lngmax { bbox.lngmax = lng }
*/
// create map
let frame = CGRect(x: 0, y: 0, width: 320, height: 320)
let map = MKMapView(frame: frame)
map.mapType = MKMapType.Satellite
// create viewing region from bounding box
var span = MKCoordinateSpan()
span.latitudeDelta = fabs(bbox.latmax - bbox.latmin)
span.longitudeDelta = fabs(bbox.lngmax - bbox.lngmin)
var center = CLLocationCoordinate2D()
center.latitude = fmax(bbox.latmin, bbox.latmax) - (span.latitudeDelta / 2.0)
center.longitude = fmax(bbox.lngmin, bbox.lngmax) - (span.longitudeDelta / 2.0)
var region = MKCoordinateRegion()
region.center = center
region.span = span
map.setRegion( region, animated: false )
// show map in playground
XCPlaygroundPage.currentPage.liveView = map
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
@AdrianBinDC
Copy link

Thank you for posting this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment