2017年1月7日土曜日

MKPointAnnotationでMapKitViewにpinを表示してみる

一つ前の投稿に、以下のコードを追加しました (ピンのIBActionを追加してます)
    // ピン置きボタン押下処理
    @IBAction func dispPin(sender: AnyObject) {
        let ido = 35.454954
        let keido = 139.631859
        let title = "横浜"
       
        execDispPin(ido, lng: keido, name: title)
    }
   
    // ピン表示関数
    func execDispPin(lat:Double, lng:Double, name:String){
        let annotation = MKPointAnnotation()

        // 位置
        annotation.coordinate = CLLocationCoordinate2DMake(lat, lng)
        // タイトル
        annotation.title = name
        // ピンを置く
        dispMap.addAnnotation(annotation)
    }

まとめるとこんな感じです
地図ボタン押す -> 地図が横浜でセンタリングされる
ピンボタンを押す -> 横浜にピンが配置される
地図のピンをクリックするとタイトルが表示されます
//
//  ViewController.swift
//  mapTest03
//

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!
   
    // ピンを表示する
    @IBAction func dispPin(sender: AnyObject) {
        let ido = 35.454954
        let keido = 139.631859
        let title = "横浜"
       
        execDispPin(ido, lng: keido, name: title)
    }
   
    func execDispPin(lat:Double, lng:Double, name:String){
        let annotation = MKPointAnnotation()

        // 位置
        annotation.coordinate = CLLocationCoordinate2DMake(lat, lng)
        // タイトル
        annotation.title = name
        // ピンを置く
        dispMap.addAnnotation(annotation)
    }
   
    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 件のコメント:

コメントを投稿