Proof of concept of creating a map with polyline support in SwiftUI. See https://codakuma.com/the-line-is-a-dot-to-you for a full tutorial.
Created
March 4, 2021 11:45
-
-
Save shaundon/00be84deb3450e31db90a31d5d5b7adc to your computer and use it in GitHub Desktop.
MapView with polyline support in SwiftUI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import MapKit | |
struct ContentView: View { | |
@State private var region = MKCoordinateRegion( | |
// Apple Park | |
center: CLLocationCoordinate2D(latitude: 37.334803, longitude: -122.008965), | |
span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01) | |
) | |
@State private var lineCoordinates = [ | |
// Steve Jobs theatre | |
CLLocationCoordinate2D(latitude: 37.330828, longitude: -122.007495), | |
// Caffè Macs | |
CLLocationCoordinate2D(latitude: 37.336083, longitude: -122.007356), | |
// Apple wellness center | |
CLLocationCoordinate2D(latitude: 37.336901, longitude: -122.012345) | |
]; | |
var body: some View { | |
MapView( | |
region: region, | |
lineCoordinates: lineCoordinates | |
) | |
.edgesIgnoringSafeArea(.all) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import MapKit | |
struct MapView: UIViewRepresentable { | |
let region: MKCoordinateRegion | |
let lineCoordinates: [CLLocationCoordinate2D] | |
func makeUIView(context: Context) -> MKMapView { | |
let mapView = MKMapView() | |
mapView.delegate = context.coordinator | |
mapView.region = region | |
let polyline = MKPolyline(coordinates: lineCoordinates, count: lineCoordinates.count) | |
mapView.addOverlay(polyline) | |
return mapView | |
} | |
func updateUIView(_ view: MKMapView, context: Context) {} | |
func makeCoordinator() -> Coordinator { | |
Coordinator(self) | |
} | |
} | |
class Coordinator: NSObject, MKMapViewDelegate { | |
var parent: MapView | |
init(_ parent: MapView) { | |
self.parent = parent | |
} | |
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { | |
if let routePolyline = overlay as? MKPolyline { | |
let renderer = MKPolylineRenderer(polyline: routePolyline) | |
renderer.strokeColor = UIColor.systemBlue | |
renderer.lineWidth = 10 | |
return renderer | |
} | |
return MKOverlayRenderer() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment