LoginSignup
1
3

More than 3 years have passed since last update.

【swift】Mapkitに表示されているpinの画像を一律すべて変える

Last updated at Posted at 2020-02-19

Mapkitのpinの画像をデフォルトのpin画像から、自分で選んだpinの画像に変更をするメモです。

1.storyboardにMapKitを貼る

storyboardにMapKitを貼ります。

2.Mapkitとコードを接続し、Mapkitの宣言をする。

weakで今回は名前を「pinChangeMap」にします。

@IBOutlet weak var pinChangeMap: MKMapView!

3.画像を登録する

左メニューにある「Assets.xassets」にpinの画像にしたい画像をドラッグし登録する。
今回名前は「mark1」にしました。

3.viewControllerにコードを書く

下記の通りコードを書きます。


import UIKit
import MapKit

 class ViewController: UIViewController ,MKMapViewDelegate{

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        // MapViewのdelegate通知先を設定
        sentouMap.delegate = self

        //MKPointAnnotationを宣言
        let annotation = MKPointAnnotation()
        // ピン(アノテーション)の緯度経度を指定
        annotation.coordinate = CLLocationCoordinate2DMake(35.681236, 139.767125)
        // アノテーションのタイトルを指定
        annotation.title = "東京駅"
        // アノテーションのサブタイトルを指定
        annotation.subtitle = "Tokyo Station"
        // mapにアノテーションを追加
        self.pinChangeMap.addAnnotation(annotation)
    }


    @IBOutlet weak var sentouMap: MKMapView!

    // mapViewのデリゲート
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

        // MKPinAnnotationViewを宣言
        let annoView = MKPinAnnotationView()
        // MKPinAnnotationViewのannotationにMKAnnotationのAnnotationを追加
        annoView.annotation = annotation
        // ピンの画像を変更
        annoView.image = UIImage(named: "mark1")
        // 吹き出しを使用
        annoView.canShowCallout = true
        // 吹き出しにinfoボタンを表示
        annoView.rightCalloutAccessoryView = UIButton(type: UIButton.ButtonType.detailDisclosure)

        return annoView   
    }
}

mapViewのデリゲートメソッドに宣言をするMKPinAnnotationViewで、imageの中に登録をした画像の名前を記載します。

let annoView = MKPinAnnotationView()
annoView.image = UIImage(named: "mark1")

これで選択した画像でPinを作成することができました。

最後に

これで任意の画像をPinにすることができました。
ただ、上記コードだとMapkitで表示しているPinすべてを一律で変更してしまうため、Pinごとに異なった画像にすることができません。
(mapViewのデリゲートメソッドで画像を変えているため)

pinごとに異なった画像で表示するのは別記事で説明したいと思います。

1
3
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
1
3