LoginSignup
13
9

More than 5 years have passed since last update.

MKMapViewに全てのピンを表示させる。

Posted at

はじめに

とても簡単にできたのにGitHubとかを読み漁ってしまった・・・。

            // 最低限の地図の大きさ
            let MINIMUM_MAP_SPAN = MKCoordinateSpanMake(0.002, 0.002)

            var topLeftCoord = CLLocationCoordinate2D(latitude: -90, longitude: 180)
            var bottomRightCoord = CLLocationCoordinate2D(latitude: 90, longitude: -180)

            // 2点間の計算を行う。
            // 現在地
            topLeftCoord.longitude = fmin(topLeftCoord.longitude, localCoordinate.longitude)
            topLeftCoord.latitude = fmax(topLeftCoord.latitude, localCoordinate.latitude)
            bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, localCoordinate.longitude)
            bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, localCoordinate.latitude)

            // ピンの位置
            topLeftCoord.longitude = fmin(topLeftCoord.longitude, pinCoordinate.longitude)
            topLeftCoord.latitude = fmax(topLeftCoord.latitude, pinCoordinate.latitude)
            bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, pinCoordinate.longitude)
            bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, pinCoordinate.latitude)

            var region = MKCoordinateRegion()
            region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5
            region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5

            // 端ギリギリにピンが立つのを避けるため少し広げる
            region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1;
            region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1;
            // 拡大しすぎの場合は最低限の縮尺にする
            region.span.latitudeDelta = fmax(MINIMUM_MAP_SPAN.latitudeDelta, region.span.latitudeDelta);
            region.span.longitudeDelta = fmax(MINIMUM_MAP_SPAN.longitudeDelta, region.span.longitudeDelta);

            self.mapView.setRegion(self.mapView.regionThatFits(region), animated: true)

ではなくて

self.mapView.showAnnotations(self.mapView.annotations, animated: true)

これで現在地も含め、全てのピンが表示される地図の倍率を出してくれた・・・。
2時間も探し求めたのに・・・・(初めに見つけた文献は間違ってて余計にはまった。)

でも、緯度経度の考え方を見直すときに使いそうなのでメモっておく。

参考

シンプルな回答
http://p-l-us-creative.com/%E3%82%A2%E3%83%97%E3%83%AA/mkmapview%E3%81%A7%E3%82%A2%E3%83%8E%E3%83%86%E3%83%BC%E3%82%B7%E3%83%A7%E3%83%B3%E3%82%84%E3%83%A6%E3%83%BC%E3%82%B6%E3%83%BC%E3%81%AE%E4%BD%8D%E7%BD%AE%E3%82%92%E3%81%99%E3%81%B9%E3%81%A6%E8%A1%A8

がんばって計算しているコード
https://gist.github.com/ttsubono/2988074

アメリカなどを含めると以下の計算式だと途中で落ちる。
http://kesin.hatenablog.com/entry/20120915/1347726989

13
9
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
13
9