【问题标题】:how to set up array for multi annotations with swift如何使用 swift 为多注释设置数组
【发布时间】:2016-04-16 16:52:34
【问题描述】:

下面的数组应该如何设置。我试图在我的地图上添加多个注释。我能够在 stackoverflow 上找到下面的代码,但它们没有显示如何设置数组。

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)
}

【问题讨论】:

  • 谢谢你的回复抢。每个数组应包含 3 项纬度、经度和字符串。我想使用坐标来绘制注释,当用户点击注释时,字符串将出现,如果字符串被点击,它将打开一个不同的视图控制器,以便访问以重用字符串

标签: ios arrays swift mkannotation mkpointannotation


【解决方案1】:

你可以这样做,例如:

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)
}

或者,或者,使用自定义类型,例如:

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)
}

或者您可以将 for 循环替换为 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)

【讨论】:

  • 完美,正是我想要的。感谢您的大力帮助
  • 我从来没有意识到我必须接受,但我只是对你的回答做了我将回到我所有其他问题并选择对我有用的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-19
  • 2021-08-27
  • 2015-05-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多