Search code examples
iosswiftxcodestructmkmapview

Accessing information from a struct


I am trying to add annotations to a map but I am having trouble accessing the different variables stored in my struct. I would like to set the name, latitude and longitude to draw off of an element in the variable restaurants. However, when trying to implement the latitude, longitude and name, I get error messages. How would I do this so that I can access any restaurant's name, latitude and longitude inside of my variable.

Here is my code.

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

Solution

  • Actually this is what you want to do:

    restaurants.forEach { placeOnMap in
        let place = MKPointAnnotation()
        place.coordinate =  CLLocationCoordinate2D(latitude: placeOnMap.latitude, longitude: placeOnMap.longitude)
        place.title = placeOnMap.name
        mapView.addAnnotation(place)
    }
    

    As mentioned by @matt in the comments section, restaurant is an array of PlacesOnMap. Your goal is to add these places to the map, so you need to convert each of these places to a CLLocationCoordinate2D instance and then add it to your map.

    Alternatively, you can do it this way:

    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)
    

    In this one, you're mapping the array of restaurants that you have into an array of MKPointAnnotation instances and then you just pass this array to the mapView.