0

I have 20 cities and store their name, latitude, and longitude in 3 arrays. here is my code in ViewDidLoad():

   var annotations:Array<MKPointAnnotation>=Array(repeating: MKPointAnnotation(), count: cityName.count)
    for i in 0 ..< annotations.count{
        annotations[i].title=cityName[i]
        annotations[i].coordinate.latitude=cityLatitude[i]
        annotations[i].coordinate.longitude=cityLongitude[i]
        mapView.addAnnotation(annotations[i])
    }

however, it only shows one pin on the map which is the last city in the array.

I tried to add the following code which I found in Stack Overflow.

   func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
    print("viewForAnnotation \(annotation.title)")
    if annotation is MKUserLocation {
        return nil
    }
    let reuseID = "pin"
    var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseID) as? MKPinAnnotationView
    if(pinView == nil) {
        pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseID)
        pinView!.canShowCallout = true
        pinView!.animatesDrop = true
    }
    return pinView
}

and add the MKMapViewDelegate in the file. But the result is still one pin on the map.

how can I add all of the pins to the map? thanks

Penny Chen
  • 79
  • 1
  • 10

0 Answers0