iosswiftmapkitapple-maps

Mapkit - How to get bounds coordinate in mapkit?


I am trying to show a map within the bounds of two coordinates. To show this, I have written this code.

    private func showMapWithinBounds() {
    let point1 = MKMapPoint(viewModel.boundsStart.location.coordinate)
    let point2 = MKMapPoint(viewModel.boundsEnd.location.coordinate)

    let mapRect = MKMapRect(x: fmin(point1.x, point2.x), y: fmin(point1.y, point2.y), width: fabs(point1.x - point2.x), height: fabs(point1.y-point2.y))
    mapView.setVisibleMapRect(mapRect, animated: true)
}

If I scroll that changes the bound latitude and longitude. So after I finish the scrolling, I want to get back that two positions' latitude and longitude which I failed. I tried this but couldn't get back the new coordinates. I want the latitude and longitude of the mentioned position in the attached image. How can I get those coordinates? enter image description here


Solution

  • Assuming that top left and bottom right corners are point1 and point2 respectively:

    Method 1

    Use MKMapView's convert method to convert a CGPoint on the view to a CLLocationCoordinate2D. If your mapView has a non-zero frame, it will be:

    let point1 = mapView.frame.origin
    let point2 = CGPoint(x: mapView.frame.maxX, y: mapView.frame.MaxY)
    
    let point1Coord = mapView.convert(point1, toCoordinateFrom: yourReferenceView)
    let point2Coord = mapView.convert(point2, toCoordinateFrom: yourReferenceView)
     
    

    Method 2 Use center and span properties of the mapView.region:

    let point1Coord = CLLocationCoordinate2D(latitude: mapView.region.center.latitude + mapView.region.span.latitudeDelta / 2, longitude: mapView.region.center.longitude - mapView.region.span.longitudeDelta / 2)
    
    let point2Coord = CLLocationCoordinate2D(latitude: mapView.region.center.latitude - mapView.region.span.latitudeDelta / 2, longitude: mapView.region.center.longitude + mapView.region.span.longitudeDelta / 2)