14.4. Phase 4: Display Searched Places on Map
The last part of our app is to show a place selected from the search results on the map and navigate to it.
The task seems complicated, but we already have the code to display the annotations for a place, right? The rest of it is pretty straightforward.
Let's open ViewController.swift file and add a method showSelectedPlace(placeItem: MKMapItem) there:
//
// ViewController.swift
// App14
//
// Created by Sakib Miazi on 6/14/23.
//
import UIKit
import MapKit
class ViewController: UIViewController {
//codes omitted...
//MARK: show selected place on map...
func showSelectedPlace(placeItem: MKMapItem){
let coordinate = placeItem.placemark.coordinate
mapView.mapView.centerToLocation(
location: CLLocation(
latitude: coordinate.latitude,
longitude: coordinate.longitude
)
)
let place = Place(
title: placeItem.name!,
coordinate: coordinate,
info: placeItem.description
)
mapView.mapView.addAnnotation(place)
}
}
//codes omitted...In the above code:
On line 16, we fetch the coordinate from the map item.
On lines 17 through 22, we center the map view around the coordinate.
On lines 23 through 27, we create a Place object from the map item.
On line 28, we add the annotation view to the place.
Now we need to call showSelectedPlace() method when a search result cell is tapped from the bottom search sheet. So, let's open SearchTableViewManager.swift file and update the tableView() method with parameter didSelectRowAt.
In the above code, on line 5, we call the showSelectedPlace() method with the selected place.
Nice! Let's try our app now.

Awesome!!! Now we built a pretty useful basic place search application!
Last updated
Was this helpful?