Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Tim Edgren
Tim Edgren
7,437 Points

How to give suggestions based on MKmapview search in a tableview

Hello guys. Im stuck and this might be a bit over the top but i hope someone can help me.

So I have a map on my app with MKmapview. Above the app i have a search option and when the search find a place it adds a annotation to that specific place. But the search takes the last suggestion when i do a search but i want to display the different results when a user search. So the user can take that suggestion and it will go back to the map and put the annotation on that location. The code that I have right now is:

func searchBarSearchButtonClicked(searchBar: UISearchBar){

    //1
    searchBar.resignFirstResponder()
    dismissViewControllerAnimated(true, completion: nil)
    if self.mapView.annotations.count != 0{
        annotation = self.mapView.annotations[0]
        self.mapView.removeAnnotation(annotation)
    }

    //2
    localSearchRequest = MKLocalSearchRequest()
    localSearchRequest.naturalLanguageQuery = searchBar.text
    localSearch = MKLocalSearch(request: localSearchRequest)
    localSearch.startWithCompletionHandler { (localSearchResponse, error) -> Void in

        if localSearchResponse == nil{
            let alertController = UIAlertController(title: nil, message: "Place Not Found", preferredStyle: UIAlertControllerStyle.Alert)
            alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alertController, animated: true, completion: nil)
            return
        }

        //3
        self.pointAnnotation = MKPointAnnotation()
        self.pointAnnotation.title = searchBar.text
        self.pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: localSearchResponse!.boundingRegion.center.latitude, longitude:     localSearchResponse!.boundingRegion.center.longitude)

        self.pinAnnotationView = MKPinAnnotationView(annotation: self.pointAnnotation, reuseIdentifier: nil)
        self.mapView.centerCoordinate = self.pointAnnotation.coordinate
        self.mapView.addAnnotation(self.pinAnnotationView.annotation!)
        self.mapItemData = localSearchResponse?.mapItems.last
    }
}

Im guessing that i should exchange the last part self.mapItemData = localSearchResponse?.mapItems.last with like a for loop like this maybe: ```for item in localSearchResponse!.mapItems { // add to a tableView }

2 Answers

Martin Wildfeuer
PLUS
Martin Wildfeuer
Courses Plus Student 11,071 Points

Hey there!

You are right, the mapItems array contains multiple items, provided multiple items are found. Let me give you a quick example on how you can display search results on a map. It is also a great showcase for the guard statement. ;)

// ...

// The following code is located in localSearch.startWithCompletionHandler
guard let localSearchResponse = localSearchResponse else {
    // Show your not found alert here
    // Note: localSearchResponse being nil does not necessarily mean no results have been found,
    // there are other reasons why this would fail. Check the error object for more details.
    return
}

// Thanks to guard, localSearchResponse is unwrapped here already and guaranteed to be non nil
// Note: You might want to remove previous annotations from the mapView at this point
mapView.removeAnnotations(mapView.annotations)

for item in localSearchResponse.mapItems {
    // item is of type MKMapItem, we create our annotation from that
    let annotation = MKPointAnnotation()

    // Set the annotation coordinate to the actual placemark
    // coordinate, rather than the center of our map view
    annotation.coordinate = item.placemark.coordinate

    // Set the annotation title to the actual name, rather than the search text
    if let name = item.name {
        annotation.title = name
    }

    // Add this annotation to our map
    self.mapView.addAnnotation(annotation)
}

//...

You will have to adjust this code to meet your needs, but this might be a starting point.

Hope that helps :)

Tim Edgren
Tim Edgren
7,437 Points

So in here

´´´ guard let localSearchResponse = localSearchResponse else { // Show your not found alert here // Note: localSearchResponse being nil does not necessarily mean no results have been found, // there are other reasons why this would fail. Check the error object for more details. return } ´´´

Is where i put the tableview code? :-)

Martin Wildfeuer
Martin Wildfeuer
Courses Plus Student 11,071 Points

The body of guard is only entered if localSearchResponse is nil. If results are found, the code is executed further. As you will want to match the tableView dataSource to the pins, you can append elements to it when a pin is created.