我正在尝试向地图添加注释,但是我无法访问存储在我的结构中的不同变量。我想设置名称,经度和纬度以从可变餐厅中提取一个元素。但是,当尝试实现纬度,经度和名称时,出现错误消息。如何执行此操作,以便可以在变量中访问任何餐厅的名称,纬度和经度。
这是我的代码。
import UIKit
import MapKit
struct PlacesOnMap {
var name: String
var latitude: Double
var longitude: Double
init(name: String, latitude: Double, longitude: Double) {
self.name = name
self.latitude = latitude
self.longitude = longitude
}
}
class MapViewController: UIViewController {
var restaurants = [PlacesOnMap(name: "Pete's", latitude: -73.2455, longitude: 65.4443),
PlacesOnMap(name: "Bake shop on 5th", latitude: 34.55555, longitude: 34.3333),
PlacesOnMap(name: "Italian", latitude: -33.4444, longitude: 43.567)
]
@IBOutlet var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
}
func setRestaurantsAnnotations() {
let places = MKPointAnnotation()
places.coordinate = CLLocationCoordinate2D(latitude: restaurants.latitude, longitude: restaurants.longitude) //I get the error: Value of type '[PlacesOnMap]' has no member 'latitude' or 'longitude'
places.title = restaurants.name //I get the error: Value of type '[PlacesOnMap]' has no member 'name'
mapView.addAnnotation(places)
}
}
实际上这是您想要做的:
restaurants.forEach { placeOnMap in
let place = MKPointAnnotation()
place.coordinate = CLLocationCoordinate2D(latitude: placeOnMap.latitude, longitude: placeOnMap.longitude)
place.title = placeOnMap.name
mapView.addAnnotation(place)
}
正如@matt在评论部分中提到的,restaurant是PlacesOnMap
的数组。您的目标是将这些地点添加到地图,因此您需要将这些地点中的每一个转换为CLLocationCoordinate2D
实例,然后将其添加到地图中。
或者,您也可以这样:
let places = restaurants.map { placeOnMap -> MKPointAnnotation in
let place = MKPointAnnotation()
place.coordinate = CLLocationCoordinate2D(latitude: placeOnMap.latitude, longitude: placeOnMap.longitude)
place.title = placeOnMap.name
return place
}
mapView.addAnnotations(places)
在此示例中,您将拥有的餐厅数组映射到MKPointAnnotation
实例数组,然后将该数组传递给mapView
。