2017年1月7日土曜日

MapKit Viewで地図を表示してみる

 0. Single Viewでprojectを作る
1. プロジェクトルート -> TARGETS(左から2番目ペイン) -> General(tabのような位置)で “Linked Frameworks and libraries”(下の方)で”Mapkit.framework”を選択して下の”+”ボタンを押す
2. Main.storyboardで”Mapkit View”をドラッグし、画面全体に広げる
3. IBOutletでmapをcodeにつなげておく
  この時点で、赤”!”のエラーが発生する(MkMapViewの定義が見つからない?)
  "import MapKit" をファイルの最初のimport定義記載部分に書くとエラーはなくなる
4.    ViewController.swiftに以下のコードを書いて、ボタンのIBAction等から呼び出す

    func execGotoSpot(){
        // 横浜の緯度経度
        let ido = 35.454954
        let keido = 139.631859
       
        let center = CLLocationCoordinate2D(latitude: ido, longitude: keido)
       
        // 1500とかだとSIGABRTが発生する(範囲が広すぎるようだ)
        let span = MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5)
       
        let theRegion = MKCoordinateRegion(center: center, span: span)
        dispMap.setRegion(theRegion, animated: true)
    }


まとめるとこんな感じ
//
//  ViewController.swift//

import UIKit
import MapKit  // 追加する

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func gotoSpot(sender: AnyObject) {
        execGotoSpot()            // 地図表示関数
    }

    @IBOutlet weak var dispMap: MKMapView!
   
    func execGotoSpot(){
        // 横浜の緯度経度
        let ido = 35.454954
        let keido = 139.631859
       
        let center = CLLocationCoordinate2D(latitude: ido, longitude: keido)
       
        // 1500とかだとSIGABRTが発生する(範囲が広すぎるようだ)
        let span = MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5)
       
        let theRegion = MKCoordinateRegion(center: center, span: span)
        dispMap.setRegion(theRegion, animated: true)
    }
}


0 件のコメント:

コメントを投稿