2016-11-09 5 views
3

マップに注釈を追加しようとしています。 私は内部に座標を持つ点の配列を持っています。 これらの座標からアノテーションを追加しようとしています。MapKitで注釈を追加 - プログラムで

私は、この定義されています:

var points: [CLLocationCoordinate2D] = [CLLocationCoordinate2D]() 
let annotation = MKPointAnnotation() 

ポイントが内部の座標を持っています。私がチェックしました。

for index in 0...points.count-1 { 
     annotation.coordinate = points[index] 
     annotation.title = "Point \(index+1)" 
     map.addAnnotation(annotation) 
    } 

ではなく、それらのすべての最後の注釈を追加...保つ:そして、私はこれを行います。 これはなぜですか? ところで、指定した注釈をタイトルなどで削除する方法はありますか?

答えて

3

各注釈は新しいインスタンスである必要があります。インスタンスは1つしか使用せず、その座標を上書きしています。だからあなたのコードを変更:

for index in 0...points.count-1 { 
    let annotation = MKPointAnnotation() // <-- new instance here 
    annotation.coordinate = points[index] 
    annotation.title = "Point \(index+1)" 
    map.addAnnotation(annotation) 
} 
+0

ありがとうございました。数時間後にそれを試して報告します。タイトルごとにアノテーションを削除することはできますか? –

+0

それは働いた。ありがとう –

+0

注釈を削除するには、注釈を見つけるまで 'map.annotations'配列を繰り返してください。次に、 'map.removeAnnotation(annotation)'を呼び出します。 – zisoft

2

あなたは以下のコード でループのためにあなたを編集することができ、私はあなたの配列が、それは私のために働いているポイントの配列

let points = [ 
    ["title": "New York, NY", "latitude": 40.713054, "longitude": -74.007228], 
    ["title": "Los Angeles, CA", "latitude": 34.052238, "longitude": -118.243344], 
    ["title": "Chicago, IL",  "latitude": 41.883229, "longitude": -87.632398] 
] 
for point in points { 
    let annotation = MKPointAnnotation() 
    annotation.title = point["title"] as? String 
    annotation.coordinate = CLLocationCoordinate2D(latitude: point["latitude"] as! Double, longitude: point["longitude"] as! Double) 
    mapView.addAnnotation(annotation) 
} 

ようになると思います。すべてあなたのために最高です。

関連する問題