Skip to content

Instantly share code, notes, and snippets.

@AdrianBinDC
Last active July 5, 2018 14:09
Show Gist options
  • Save AdrianBinDC/a8da4748181d86203689bc369fa01ed2 to your computer and use it in GitHub Desktop.
Save AdrianBinDC/a8da4748181d86203689bc369fa01ed2 to your computer and use it in GitHub Desktop.
Set MKMapRegion to display a specific zoom scale

Set Zoom Scale on Map Region in Swift

MKCoordinateRegionMakeWithDistance can be used to make a region with a specified distance (in meters).

Here is the method signature:

func MKCoordinateRegionMakeWithDistance(_ centerCoordinate: CLLocationCoordinate2D, 
                                        _ latitudinalMeters: CLLocationDistance, 
                                        _ longitudinalMeters: CLLocationDistance) -> MKCoordinateRegion

Use an extension to get your desired distance and convert it into meters.

extension Double {
  func convert(from originalUnit: UnitLength, to convertedUnit: UnitLength) -> Double {
    return Measurement(value: self, unit: originalUnit).converted(to: convertedUnit).value
  }
}

Then, adjust the region using MKMapView's regionThatFits() method and plug in the desired region. MKMapView will figure the adjusted region and lastly, set the new adjusted region.

  let viewRegion = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2D(latitude: latitude, longitude: longitude), miles.convert(from: .miles, to: .meters), miles.convert(from: .miles, to: .meters))
  let adjustedRegion = mapView.regionThatFits(viewRegion)
  mapView.setRegion(adjustedRegion, animated: true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment