Using an Array to Transfer Coordinates To Be Placed on MkMapView

182 views Asked by At

I have one view controller that lets the user input coordinates into textfields and updates these coordinates (as well as a title) into an array. In my MapView VC, I want to be able to place pins down according to what the user has inputed. However, when I run the code, the input coordinates are not read and nothing is placed on the MapView. I have a hunch that either I am not saving these locations properly, or my pin placing is not working, but I am not sure where the error could be.

Input Coordinates:

import UIKit
import CoreLocation

// here I initialize my array locations
var locations: [Dictionary<String, Any>] = []

class OtherVC: UIViewController {

@IBOutlet weak var latitudeField: UITextField!
@IBOutlet weak var longitudeField: UITextField!

@IBOutlet weak var titleTextField: UITextField!
var coordinates = [CLLocationCoordinate2D]()

override func viewDidLoad() {
    super.viewDidLoad()
}

// this IBOutlet takes the input from the textfield
@IBAction func addToMap(_ sender: Any) {
    let lat = latitudeField.text!
    let long = longitudeField.text!
    let title = titleTextField.text!
    let location: [String: Any] = ["title": title, "latitude": lat, "longitude": long]
    locations.append(location)

}

Below is the code for my MapView:

import UIKit
import MapKit
class MapViewController: UIViewController, MKMapViewDelegate {

@IBOutlet weak var mapView: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()
    mapView.delegate = self


    //iterates each location in my array to pull the title and coordinate
    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)
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    let identifier = "pinAnnotation"
    var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView

    if annotationView == nil {
        annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
        annotationView?.canShowCallout = true
    }

    annotationView?.annotation = annotation
    return annotationView
}
}


}
0

There are 0 answers