how to set up array for multi annotations with swift

前端 未结 1 1667
慢半拍i
慢半拍i 2020-12-28 20:32

How should the array below be set. Im trying to add multiple annotations onto my map. I was able to find the code below on stackoverflow but they did not show how to set up

相关标签:
1条回答
  • 2020-12-28 21:18

    You could do, for example:

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

    Or, alternatively, use a custom type, e.g.:

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

    Or you can replace that for loop with 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)
    
    0 讨论(0)
提交回复
热议问题