-
-
Save audiocommander/6c70f5acf8de2daba2c03c429370ca69 to your computer and use it in GitHub Desktop.
Center a MKMapView given a GeoJSON bounding box
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for posting this!