|
| 1 | +# SwiftUI-MapView |
| 2 | + |
| 3 | +Basic Map view in Swift UI. |
| 4 | + |
| 5 | +<img width="1427" alt="Screenshot 2019-12-12 at 11 54 28 PM" src="https://user-images.githubusercontent.com/19596311/70739799-acf26a00-1d3d-11ea-8e97-bd72849f3ae8.png"> |
| 6 | + |
| 7 | + |
| 8 | +### Create MapView in SwiftUI. |
| 9 | + |
| 10 | +```swift |
| 11 | + |
| 12 | +import SwiftUI |
| 13 | +import MapKit |
| 14 | + |
| 15 | +struct MapView: UIViewRepresentable { |
| 16 | + |
| 17 | + let landmarks = LandmarkAnnotation.requestMockData() |
| 18 | + |
| 19 | + func makeCoordinator() -> MapViewCoordinator { |
| 20 | + MapViewCoordinator(self) |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + - Description - Replace the body with a make UIView(context:) method that creates and return an empty MKMapView |
| 25 | + */ |
| 26 | + func makeUIView(context: Context) -> MKMapView{ |
| 27 | + MKMapView(frame: .zero) |
| 28 | + } |
| 29 | + |
| 30 | + func updateUIView(_ view: MKMapView, context: Context){ |
| 31 | + //If you changing the Map Annotation then you have to remove old Annotations |
| 32 | + //mapView.removeAnnotations(mapView.annotations) |
| 33 | + view.delegate = context.coordinator |
| 34 | + view.addAnnotations(landmarks) |
| 35 | + } |
| 36 | +} |
| 37 | +``` |
| 38 | + |
| 39 | +### Mixing UIKit inside SwiftUI by using Coordinator. |
| 40 | + |
| 41 | +```swift |
| 42 | +import MapKit |
| 43 | + |
| 44 | +/* |
| 45 | + Coordinator for using UIKit inside SwiftUI. |
| 46 | + */ |
| 47 | +class MapViewCoordinator: NSObject, MKMapViewDelegate { |
| 48 | + |
| 49 | + var mapViewController: MapView |
| 50 | + |
| 51 | + init(_ control: MapView) { |
| 52 | + self.mapViewController = control |
| 53 | + } |
| 54 | + |
| 55 | + func mapView(_ mapView: MKMapView, viewFor |
| 56 | + annotation: MKAnnotation) -> MKAnnotationView?{ |
| 57 | + //Custom View for Annotation |
| 58 | + let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "customView") |
| 59 | + annotationView.canShowCallout = true |
| 60 | + //Your custom image icon |
| 61 | + annotationView.image = UIImage(named: "locationPin") |
| 62 | + return annotationView |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +``` |
| 67 | + |
| 68 | +## Checkout my complet blog [here](https://medium.com/flawless-app-stories/mapkit-in-swiftui-c0cc2b07c28a). |
0 commit comments