Search code examples
iosswiftlocationmkmapview

How can I zoom Mapview with giving corner locations


I have an array like [[39.1216, 40.5127],[40.5081, 40.5127],[40.5081, 41.1076],[39.1216, 41.1076]] this and this locations gives me corner coordinates of a city . [topleft,topRight,botRight,botLeft]

When user select a city I want to zoom mapview until corners of mapview matches this locations. I searched but cant find any solution. How can I achieve this ?

I can get center position of this coordinates but How can I calculate latitudinalMeters and longitudinalMeters according to corners locations?

  let region = MKCoordinateRegion.init(center: location, latitudinalMeters: "calculations", longitudinalMeters: "calculations")

Solution

  • You can get the difference (the delta) between your latitudes and longitudes and then use MKCoordinateSpan and MKCoordinateRegion to set the initial visible region of the map.

        let latDelta = topLeft.latitude - bottomRight.latitude
        let lonDelta = topLeft.longitude - bottomRight.longitude
        let span = MKCoordinateSpan(latitudeDelta: fabs(latDelta), longitudeDelta: fabs(lonDelta))
        
        let region = MKCoordinateRegion(center: lake.midCoordinate, span: span)
        
        mapView.region = region