Skip to main content

97 - MKMapView - OLD

Using Apple Maps - MapKit (pre 2023 WWDC)

import MapKit

...


@State private var region = MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: 51.507222, longitude: -0.1275),
span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))


var body: some View {
VStack {
VStack {

Map(
coordinateRegion: $region,
showsUserLocation: true,
userTrackingMode: .constant(.follow)
)


}
.padding()
}
}

This is simple and really limited map view. No polylines etc. Has only simple annotations

  • MapPin
  • MapMarker
  • MapAnnotation

Advanced Map View - MKMapView

Create custom SwiftUI view based on older UIView, protocol UIViewRepresentable

struct SomeUIViewBasedView: UIViewRepresentable {
@binding var someValue: SomeValueType

func makeUIView(context: Context) -> UIViewOfSomeKind {
return UIViewOfSomeKind()
}

func updateUIView(_ view: UIViewOfSomeKind, context: Context) {
view.someAttribute = someValue
}
}
import SwiftUI
import MapKit

struct MapView: UIViewRepresentable {
let region: MKCoordinateRegion
let lineCoordinates: [CLLocationCoordinate2D]

func makeCoordinator() -> Coordinator {
Coordinator(self)
}

func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView()
mapView.delegate = context.coordinator
mapView.region = region
mapView.showsUserLocation = true

let polyline = MKPolyline(coordinates: lineCoordinates, count: lineCoordinates.count)
mapView.addOverlay(polyline)

return mapView
}

func updateUIView(_ view: MKMapView, context: Context) {
view.setRegion(region, animated: true)
let polyline = MKPolyline(coordinates: lineCoordinates, count: lineCoordinates.count)
view.addOverlay(polyline)
view.removeOverlays(view.overlays.dropLast())
}
}

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()
}

}

Using Google maps in SwiftUI

https://developers.google.com/codelabs/maps-platform/maps-platform-ios-swiftui