Adam Adam - 1 year ago 75
iOS Question

Swift adding annotations on map

Trying to make some annotations on the map. But can't get around it. the code I'm using is

// Names
names = ["Ben", "Big", "Hawk", "Enot", "Wiltons", "Scott's", "The Laughing"]

// Latitudes, Longitudes
coordinates = [
[51.519066, -0.135200],
[51.513446, -0.125787],
[51.465314, -0.214795],
[51.507747, -0.139134],
[51.509878, -0.150952],
[51.501041, -0.104098],
[51.485411, -0.162042],
[51.513117, -0.142319]

Answer Source

You really haven't tried much. But take a look at this. The function addAnnotation takes an array of type CLLocation, which is what you should use. So make the array look like this to initialize CLLocation objects. I assume you already have a working rendered map, mapView object, etc.

let coords = [  CLLocation(latitude: xxxx, longitude: xxxx),
   CLLocation(latitude: xxx, longitude: xxx),
   CLLocation(latitude: xxx, longitude:xxx)

here is a function that can take that array, and loops through each element and adds it as an annotation to the mapView (not yet rendered)

func addAnnotations(coords: [CLLocation]){
        for coord in coords{
            let CLLCoordType = CLLocationCoordinate2D(latitude: coord.coordinate.latitude,
                                                      longitude: coord.coordinate.longitude);
            let anno = MKPointAnnotation();
            anno.coordinate = CLLCoordType;


Finally, you need to use the MKMapViewDelegate delegate to use one of its automatically called methods, when a new annotation is added, so we can queue and render it. This would be unnecessary if you were adding annotations once, but it is good to have them added like this so you can manipulate them later.

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation{
        return nil;
        let pinIdent = "Pin";
        var pinView: MKPinAnnotationView;
        if let dequeuedView = mapView.dequeueReusableAnnotationViewWithIdentifier(pinIdent) as? MKPinAnnotationView {
            dequeuedView.annotation = annotation;
            pinView = dequeuedView;
            pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: pinIdent);

        return pinView;

Do not just add this code and expect it to work, make sure you incorporate it correctly, in the right areas of your project. Do comment if you have further questions.


remember to inherit the MKMapViewDelegate protocol into the controller your using.

Make sure you actually call addAnnotations, in ViewDidLoad, and pass through coords array. Which can be defined in ViewDidLoad.

Make sure the mapView method is not in ViewDidLoad but a member of the controller.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download