コンテンツにスキップ

指定した座標にピンを立てる

Preview mapkit004

import SwiftUI
import MapKit

struct Point: Identifiable {
    let id = UUID()
    let coordinate: CLLocationCoordinate2D
}

struct ContentView: View {
    @State private var points: [Point] = [
        Point(coordinate: .init(latitude: 37.521528012588584,
                                longitude: 139.93847299738366))
    ]

    @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, annotationItems: points) { points in
            MapMarker(coordinate: points.coordinate)
        }
    }
}

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

//
//  ViewController.swift
//  MapKit004
//
//  Copyright © 2016年 FaBo, Inc. All rights reserved.
//

import UIKit
import MapKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // MapViewを生成.
        let myMapView: MKMapView = MKMapView()
        myMapView.frame = self.view.frame

        // 経度、緯度.
        let myLatitude: CLLocationDegrees = 37.331741
        let myLongitude: CLLocationDegrees = -122.030333

        // 中心点.
        let center: CLLocationCoordinate2D = CLLocationCoordinate2DMake(myLatitude, myLongitude)

        // MapViewに中心点を設定.
        myMapView.setCenter(center, animated: true)

        // 縮尺.
        // 表示領域.
        let mySpan: MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
        let myRegion: MKCoordinateRegion = MKCoordinateRegion(center: center, span: mySpan)

        // MapViewにregionを追加.
        myMapView.region = myRegion

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

        // ピンを生成.
        let myPin: MKPointAnnotation = MKPointAnnotation()

        // 座標を設定.
        myPin.coordinate = center

        // タイトルを設定.
        myPin.title = "タイトル"

        // サブタイトルを設定.
        myPin.subtitle = "サブタイトル"

        // MapViewにピンを追加.
        myMapView.addAnnotation(myPin)
    }
}

Reference