LoginSignup
38
38

More than 5 years have passed since last update.

SwiftでMKMapView上にピン(MKPointAnnotation)置いてみた

Last updated at Posted at 2014-07-16

必要なフレームワーク

プロジェクト名 -> TARGETS -> Generalの順で選択し、下の方にある「Linked Frameworks and Libraries」の+ボタンで以下のフレームワークを追加。MKMapViewを使うには以下のフレームワークが必要である。

MapKit.framework

MapViewControllerの追加

「AppDelegate.swift」の下あたりで右クリックし、「New file...」をクリック。次に、メニューの中から「Cocoa Touch Class」を選択してから、「Next」をクリック。そして、「Subclass of:」で「UIViewController」を選択し、Class名を「MapViewController」(任意)にしたら、Next -> Create で追加完了。

AppDelegateでMapViewControllerをRootViewに設定

Objective-CのようにViewControllerをimportしなくてもよくなった。
これは楽だ。

AppDelegate.swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        // Override point for customization after application launch.
        self.window!.backgroundColor = UIColor.whiteColor()
        self.window!.makeKeyAndVisible()

        //-----------------------ここから--------------------------//

        //FirstViewControllerをRootViewに設定する
        var fvc = FirstViewController(nibName:nil,bundle:nil);
        self.window!.rootViewController = fvc;

        //-----------------------ここまで--------------------------//

        return true
    }

MapViewControllerの実装

次に、MapViewControllerを実装。
Objective-Cのときより、確実に書く量減ったなー

MapViewController.swift

import UIKit
import MapKit  //MapKit.frameworkをインポート

class MapViewController: UIViewController , MKMapViewDelegate{  //MKMapViewDelegateを宣言

    //マップ
    var mapView: MKMapView = MKMapView()
    //長押し検知器
    var longtapGesture: UILongPressGestureRecognizer = UILongPressGestureRecognizer()

    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        // Custom initialization
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        //マップの設定
        //マップにフレームサイズを設定
        self.mapView.frame = CGRectMake(0,20,self.view.bounds.size.width,self.view.bounds.size.height)
        //マップのDelegateを設定(上記のMKMapDelegate)
        self.mapView.delegate = self
        self.view.addSubview(self.mapView)

        //初期位置を設定
        //経度、緯度からメルカトル図法の点に変換する
        var centerCoordinate : CLLocationCoordinate2D = CLLocationCoordinate2DMake(35.665213,139.730011)
        let span = MKCoordinateSpanMake(0.003, 0.003) //小さい値であるほど近づく
        //任意の場所を表示する場合、MKCoordinateRegionを使って表示する -> (中心位置、表示領域)
        var centerPosition = MKCoordinateRegionMake(centerCoordinate, span)
        self.mapView.setRegion(centerPosition,animated:true)

        //長押し検知器の設定
        //長押し時に呼びだすメソッド
        self.longtapGesture.addTarget(self, action: "longPressed:")
        //マップに長押し検知器を追加
        self.mapView.addGestureRecognizer(self.longtapGesture)
    }

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

    func longPressed(sender: UILongPressGestureRecognizer){

        //指を離したときだけ反応するようにする
        if(sender.state != .Began){
            return
        }

        //senderから長押しした地図上の座標を取得
        var location = sender.locationInView(self.mapView)
        //CLLocationCoordinate2Dに変換
        var mapPoint:CLLocationCoordinate2D = self.mapView.convertPoint(location, toCoordinateFromView: self.mapView)

        //ピンを生成
        var theRoppongiAnnotation = MKPointAnnotation()
        //ピンを置く場所を設定
        theRoppongiAnnotation.coordinate  = mapPoint
        //ピンのタイトルの設定
        theRoppongiAnnotation.title       = "ピン置いたぜぇ〜"
        //ピンのサブタイトルを設定
        theRoppongiAnnotation.subtitle    = "ワイルドだろぅ〜?"
        //ピンを地図上に追加
        self.mapView.addAnnotation(theRoppongiAnnotation)
    }

}

これで、地図が表示され、長押ししたところにピンが出現するようになります。

38
38
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
38