LoginSignup
7
2

More than 5 years have passed since last update.

[iOS] 地図(MKMapView)にピンが表示されないときに確認すること

Posted at

これはなに

Stack Overflow の mapkit タグを購読していると、「地図にピンが表示されないよ助けて!」という質問をよく目にします。大抵以下の3パターンが原因なので、確認すべき点をまとめてみます。

1. delegate をセットしているか

意外と MKMapViewDelegate をセットし忘れているケースが多いです。

まずはデリゲートプロトコルを宣言しているか確認。

class ViewController: UIViewController, MKMapViewDelegate {

つぎに delegate プロパティに処理を委譲する対象をセットしているか確認。

mapView.delegate = self

Storyboard でセットする場合。

image.png

そして、デリゲートメソッドを実装しているか確認。

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation {
        return nil
    }

    let reuseId = "pin"
    var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
    if pinView == nil {
        pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
    }
    else {
        pinView?.annotation = annotation
    }

    return pinView
}

これでピンが表示されるはず!

2. MKAnnotationView を使っていないか

ピンを表示する場合は MKAnnotationView ではなく MKPinAnnotationView を使わないと何も表示されません。

ちなみに MKAnnotationView はピンに画像を使いたいとき等に使用します。

pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView?.image = UIImage(named: "Laugh")

3. 緯度経度が間違っていないか

たまに緯度(latitude)と経度(longitude)が逆になっているケースも見かけます。CLLocationCoordinate2D を返す

public func CLLocationCoordinate2DMake(_ latitude: CLLocationDegrees, _ longitude: CLLocationDegrees) -> CLLocationCoordinate2D

を多用することになりますが、それぞれの引数にセットする値を間違えないように注意しましょう。

例えば

  • 緯度: 35.658034
  • 経度: 139.701636

の場合は

let coordinate = CLLocationCoordinate2DMake(35.658034, 139.701636)

となります。

7
2
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
7
2