/ / wie man ein Array für Multi Annotations mit Swift - ios, Arrays, Swift, Mkannotation, Mkpointannotation einrichtet

Wie man ein Array für Mehrfachanmerkungen mit swift - ios, arrays, swift, mkannotation, mkpointannotation einrichtet

Wie soll das Array unten eingestellt werden? Ich versuche, meiner Karte mehrere Anmerkungen hinzuzufügen. Ich konnte den Code unten auf stackoverflow finden, aber er zeigte nicht, wie das Array eingerichtet wird.

var objects = [
//how should the array be setup here
]

for objecters in objects!{
if let latit = objecters["Coordinates"]["Latitude"]{
self.latitudepoint = latit as! String
self.map.reloadInputViews()
}
else {
continue
}
if let longi = objecters["Coordinates"]["Longitude"]{
self.longitudepoint = longi as! String
self.map.reloadInputViews()
}
else {
continue
}
var annotation = MKPointAnnotation()
var coord = CLLocationCoordinate2D(latitude: Double(self.latitudepoint)!,longitude: Double(self.longitudepoint)!)
mapView.addAnnotation(annotation)
}

Antworten:

21 für die Antwort № 1

Sie könnten zum Beispiel tun:

let locations = [
["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 location in locations {
let annotation = MKPointAnnotation()
annotation.title = location["title"] as? String
annotation.coordinate = CLLocationCoordinate2D(latitude: location["latitude"] as! Double, longitude: location["longitude"] as! Double)
mapView.addAnnotation(annotation)
}

Oder verwenden Sie alternativ einen benutzerdefinierten Typ, z.

struct Location {
let title: String
let latitude: Double
let longitude: Double
}

let locations = [
Location(title: "New York, NY",    latitude: 40.713054, longitude: -74.007228),
Location(title: "Los Angeles, CA", latitude: 34.052238, longitude: -118.243344),
Location(title: "Chicago, IL",     latitude: 41.883229, longitude: -87.632398)
]

for location in locations {
let annotation = MKPointAnnotation()
annotation.title = location.title
annotation.coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
mapView.addAnnotation(annotation)
}

Oder du kannst das ersetzen for Schleife mit map:

let annotations = locations.map { location -> MKAnnotation in
let annotation = MKPointAnnotation()
annotation.title = location.title
annotation.coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
return annotation
}
mapView.addAnnotations(annotations)