コンテンツにスキップ

地図の表示

Preview mapkit001

//
//  ViewController.swift
//  MapKit001
//
//  Copyright © 2021年 FaBo, Inc. All rights reserved.
//

import SwiftUI
import MapKit

struct ContentView: View {
    @State private var region = MKCoordinateRegion(
        center: CLLocationCoordinate2D(latitude: 37.521528012588654,
                                       longitude: 139.93847299738346),
        span: MKCoordinateSpan(latitudeDelta: 0.005,
                               longitudeDelta: 0.005)
    )
    var body: some View {
        Map(coordinateRegion: $region)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
    }
}
//
//  ViewController.swift
//  MapKit001
//
//  Copyright © 2016年 FaBo, Inc. All rights reserved.
//

import UIKit
import MapKit

class ViewController: UIViewController, MKMapViewDelegate {

    // MapView.
    var myMapView : MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // MapViewの生成.
        myMapView = MKMapView()

        // MapViewのサイズを画面全体に.
        myMapView.frame = self.view.bounds

        // Delegateを設定.
        myMapView.delegate = self

        // MapViewをViewに追加.
        self.view.addSubview(myMapView)

        // 中心点の緯度経度.
        let myLat: CLLocationDegrees = 37.506804
        let myLon: CLLocationDegrees = 139.930531
        let myCoordinate: CLLocationCoordinate2D = CLLocationCoordinate2DMake(myLat, myLon)

        // 縮尺.
        let myLatDist : CLLocationDistance = 100
        let myLonDist : CLLocationDistance = 100

        // Regionを作成.
        let myRegion: MKCoordinateRegion = MKCoordinateRegion(center: myCoordinate, latitudinalMeters: myLatDist, longitudinalMeters: myLonDist);

        // MapViewに反映.
        myMapView.setRegion(myRegion, animated: true)

    }

    // Regionが変更された時に呼び出されるメソッド.
    func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
        print("regionDidChangeAnimated")
    }
}

Reference