2016-10-23 3 views
1

私のswiftアプリケーションでは、私はMapKitを使用しており、いくつかの注釈をマップに追加しています。注釈ビューが画面の端に近づいている場合にのみ、その注釈ビューに地図を配置するにはどうすればよいですか?

現在、この質問のおかげで、Trying to get the span size in meters for an iOS MKCoordinateSpan私はユーザーがそれを押したときに注釈にマップを集中させる機能を作成することができました。これはそれのためのコードです:

let span = mapView.region.span 
let centerView = mapView.region.center 

let loc1 = CLLocation(latitude: centerView.latitude - span.latitudeDelta * 0.5, longitude: centerView.longitude) 
let loc2 = CLLocation(latitude: centerView.latitude + span.latitudeDelta * 0.5, longitude: centerView.longitude) 
let loc3 = CLLocation(latitude: centerView.latitude, longitude: centerView.longitude - span.longitudeDelta * 0.5) 
let loc4 = CLLocation(latitude: centerView.latitude, longitude: centerView.longitude + span.longitudeDelta * 0.5) 

let metersInLatitude = loc1.distance(from: loc2) 
let metersInLongitude = loc3.distance(from: loc4) 

let center:CLLocationCoordinate2D = (MyCustomAnnotation?.coordinate)! 
let coordinateRegion = MKCoordinateRegionMakeWithDistance(center, metersInLatitude, metersInLongitude) 
mapView.setRegion(coordinateRegion, animated: true) 

、それが正常に動作します - 現在のズームレベルを維持しながら、ユーザーが任意のMyCustomAnnotationをクリックするたびに、それはマップを中心に説明します。

このコードを少し変更したいので、ポイントが画面の4つのエッジの1つに近い場合にのみポイントを中心にします。注釈点が画面の中心に近いところにあるときは、地図を中心にすべきではありません。どうしたらいいですか? MyCustomAnnotation?.coordinateとその4点で設定された領域の違いを(何とか)確認することを考えました。loc1loc2loc3loc4ですが、どのように処理するかはわかりません。あなたはそれで私を助けることができますか?

答えて

1

注釈の位置を4つのエッジすべてと比較するのではなく、中心の位置からの距離を確認します。

let distance = center.distanceFromLocation(annotationLocation) 

この距離が特定の半径より大きい場合、アノテーションはエッジの1つに近くなります。

if distance > radius { 
    //center annotation 
} 

半径は領域スパンから計算できます。

let radius = min(region.span.longitudeDelta, region.span.latitudeDelta) * 0.3 
+0

なぜ乗算は0.3ですか? –

+0

これはあなたが定義できる単なる要素です – Hannes

関連する問題