Jay Wilson developer. creator. coffee drinker.

How to get the current MKCoordinateRegion from a MapCameraPosition

Struggled with this a bit, so figured I would write how I did this.

Goal to achieve: Get the MKCoordinateRegion of the map I'm looking at.

What I tried and did not work:

struct MapSearchView: View {
	@State private var position = MapCameraPosition.automatic
	@State private var mapRegion: MKCoordinateRegion = .init()

	var body: some View {
		Map(position: $position)
		.onChange(of: position) {
			print(position.region)
		}
  }
}

This would always print nil even though it's supposed to be the current region.

What I ended up getting to work:

struct MapSearchView: View {
	@State private var position = MapCameraPosition.automatic
	@State private var mapRegion: MKCoordinateRegion = .init()

	var body: some View {
		Map(position: $position)
		.onMapCameraChange { mapCameraUpdateContext in
			mapRegion = mapCameraUpdateContext.region
		}
  }
}

I had to use the specific onMapCameraChange to get the region and then update a state variable. I can then use that however I want.

If you liked this post, consider buying me a coffee.

Or donate to Lambda Legal to help fight for trans and LGBTQIA+ rights.

Subscribe to my posts via your favorite feed reader.