コンテンツにスキップ

国土地理院の地図を表示

//  cat files | awk -F'[/]' '{system("curl --create-dirs -o "$6"/"$7"/"$8" "$0)}' 

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 {
    class KokudoMapOverlay: MKTileOverlay {
      override func url(forTilePath path: MKTileOverlayPath) -> URL {
        let tilePath = Bundle.main.url(
          forResource: "\(path.y)",
          withExtension: "png",
          subdirectory: "tiles/\(path.z)/\(path.x)",
          localization: nil)
        if let tile = tilePath {
          return tile
        } else {
            let tileUrl =
              "https://cyberjapandata.gsi.go.jp/xyz/std/\(path.z)/\(path.x)/\(path.y).png"
            print(tileUrl)
            return URL(string: tileUrl)!
        }
      }
    }

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

    private let overlay = KokudoMapOverlay(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)
    }
}

コマンド

cat files | awk -F'[/]' '{system("curl --create-dirs -o "$6"/"$7"/"$8" "$0)}' 

Reference