Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
MapView with polyline support in SwiftUI
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)
}
}
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