Skip to content

Instantly share code, notes, and snippets.

@syou007
Created May 24, 2016 02:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syou007/7f213ffb01620a2686c985341bb51b5a to your computer and use it in GitHub Desktop.
Save syou007/7f213ffb01620a2686c985341bb51b5a to your computer and use it in GitHub Desktop.
MKMapViewに全てのピンを表示させる。 ref: http://qiita.com/syou007/items/f6d190c08ee57cf6455f
// 最低限の地図の大きさ
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment