Connecting MapKit annotations to a table view

Viewed 1016

I have view controller where the bottom half is tableview and the top half is a map. When it loads I call an API to get nearby places and load those places into an array. After the array is loaded I loop through the array to set an annotation for each location's lat, lon, and name and that same array is the data for the table view. What I am trying to do is connect the table cell and the annotation.

When someone taps the tableview I want the associated annotation to be selected with a call out for picking it. When someone taps the annotation I want the tableview to display the associated cell in the table view and highlight it. I researched and found the mapView function didSelect for processing the selected annotation but I don't know how to (or if you can) connect the 2. Right now I am faking it out by putting the array position into the annotation's subtitle and this allows me to read all the details from that position but it seems like the wrong way to do it.

...// load places into an array
            curBlipPlace.name = yelp.name
            curBlipPlace.distance = yelp.distance
            curBlipPlace.address1 = yelp.address1
            curBlipPlace.lat = yelp.lat
            curBlipPlace.lon = yelp.lon
            curBlipPlace.yelpId = yelp.yelpId
            curBlipPlace.yelp = yelp
            curBlipPlace.yelpArrayPosition = yelp.arrayPosition
            self.blipPlaces.append(curBlipPlace)

..// After filling array, sort it, loop to load annotations, and load to table
            self.blipPlaces.sort { $0.distance ?? 9999 < $1.distance ?? 9999 }
            for i in 0..<self.blipPlaces.count {
                if let lat = self.blipPlaces[i].lat, let lon = self.blipPlaces[i].lon {
                    let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon)
                    let annotation = MKPointAnnotation()
                    annotation.coordinate = coordinate
                    annotation.title = self.blipPlaces[i].name
                    annotation.subtitle = String(i)

                    self.map.addAnnotation(annotation)
                }
            }

            self.PlaceTableView.reloadData()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = PlaceTableView.dequeueReusableCell(withIdentifier: "fileCell", for: indexPath) as! BlipFileTVCell
    cell.placeLabel.text = "\(indexPath.row): \(blipPlaces[indexPath.row].name) - \(blipPlaces[indexPath.row].distance ?? 999)"
    return cell
}

..// Rube Goldberg way of connecting table cell and annotation by forcing array position into subTitle
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    print("CLICKED: \(String(describing: view.annotation?.title))")
    if let tempString = (view.annotation?.subtitle) as? String {
        print("ok... \(tempString)")
        if let tempInt = Int(tempString) {
            print(self.blipPlaces[tempInt].name)
        }
    }
}

Is there a better way to connect the annotation and the table cell? Is there a way to have the cell tap activate the annotation?

Also, since the tapped annotation may be the last cell in teh table, is there a way to "move" the table cell up if its off screen? If someone selects an annotation for the last item in the list is there a way to get the table cell to "scroll up" so that one is viewable and not off screen?

-dan

1 Answers

Implement custom annotation.

class CustomAnnotation: MKPointAnnotation {
    var index: Int!
}

Add the custom annotation to mapView.

let annotation = CustomAnnotation()
annotation.coordinate = coordinate
annotation.title = "title"
annotation.subtitle = "subtitle"
annotation.index = 0 // 0...n
self.mapView.addAnnotation(annotation)

You can get index in mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView).

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    if let annotation = view.annotation as? CustomAnnotation {
        print(annotation.index)
        // Get the cell by index
        // You can use `cellForRowAtIndexPath:`
        // Then select the cell
    }
}

EDITED:

// when the table view is clicked 
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    for annotation in mapView.annotations {
        if let annotation = annotation as? CustomAnnotation, annotation.index == indexPath.row {
            // select annotation and show callout
            mapView.selectAnnotation(annotation, animated: true)
        }
    }
}
Related