Jay as a memoji Jay Wilson

How to get the current MKCoordinateRegion from a MapCameraPosition

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

Published:

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.


Written by Jay Wilson on


Thanks for reading! If you found this post useful consider buying me a coffee, so I can keep making posts like this.

No comments yet. Share on mastodon and see your comment or write a post on your blog if you support Webmentions

These people reposted this post on various platforms around the internet.

These people liked this post on various platforms around the internet.

These people bookmarked this post on various platforms around the internet.

Powered by Webmentions