コンテンツにスキップ

国土地理院の地図を表示

import SwiftUI
import MapKit

struct KokudoMapView: UIViewRepresentable {
    var region: MKCoordinateRegion
    var overlay: MKTileOverlay

    class Coordinator: NSObject, MKMapViewDelegate {
        var parent: KokudoMapView

        init(_ parent: KokudoMapView) {
            self.parent = parent
        }

        func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
            let renderer = MKTileOverlayRenderer(overlay: overlay)
            return renderer
        }
    }

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

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

    func updateUIView(_ mapView: MKMapView, context: Context) {
        mapView.delegate = context.coordinator

        let overlays = mapView.overlays
        mapView.addOverlay(overlay)
        mapView.setRegion(region, animated: true)
        for overlay in overlays {
            if overlay is MKTileOverlay {
                mapView.removeOverlay(overlay)
            }
        }
    }
}

struct ContentView: View {

    private let region = MKCoordinateRegion(
            center: CLLocationCoordinate2D(latitude: 37.521528012588654,
                                           longitude: 139.93847299738346),
            span: MKCoordinateSpan(latitudeDelta: 0.005,
                                   longitudeDelta: 0.005)
    )

    private let overlay = MKTileOverlay(urlTemplate: "https://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png")

    var body: some View {
        KokudoMapView(region: region, overlay: overlay)
                    .edgesIgnoringSafeArea(.all)
                    .statusBar(hidden: true)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
    }
}

Reference