Friday, June 28, 2019

How to create Map view in SwiftUI?


Project : https://github.com/EdyLucky/MapView
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project.
In the template selector, select iOS as the platform, select the Single View Apptemplate, and then click Next.

Enter “MapView” as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

In Canvas on the right click Resume to display the preview. If the canvas is hidden select Editor > Editor and Canvas to show it.

After creating project MapKit needs to be imported and UIViewRepresentable  protocol declared. 


There might be errors regarding the adopted protocol , we will fix them in the next steps. This error is due to UIViewRepresentable protocol which has two requirements you need to add: a makeUIView(context:) method that creates an MKMapView, and an updateUIView(_:context:) method that configures the view and responds to any changes.

Replace the body property with a makeUIView(context:) method that creates and returns an empty MKMapView.


The next step is to create an updateUIView(_:context:) method that sets the map view’s region to the correct coordinates to center the map on Apple’s headquarters. Because MKMapView is a UIView subclass, you’ll need to switch to a live preview to see the map.




CLLocationCoordinate2D - The latitude and longitude associated with a location, specified using the WGS 84 reference frame.


MKCoordinateSpan - Delta values are used in this structure to indicate the desired zoom level of the map, with smaller delta values corresponding to a higher zoom level.

MKCoordinateRegion - A rectangular geographic region centered around a specific latitude and longitude.

5 comments:

  1. Hi Mario, you can add pin by inserting following code inside updateUIView method

    let annotation = MKPointAnnotation()
    annotation.coordinate = coordinate

    annotation.title = "My Location"
    view.addAnnotation(annotation)

    ReplyDelete
  2. Great article! Here's a detailed one on SwiftUI and Map Kit, for those looking to learn more https://www.iosapptemplates.com/blog/swiftui/map-view-swiftui

    ReplyDelete
  3. Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained! what county am i in now

    ReplyDelete
  4. If your looking for Online Illinois license plate sticker renewals then you have need to come to the right place.We offer the fastest Illinois license plate sticker renewals in the state. Process Of Free Garmin Map Update

    ReplyDelete