Beta
Search SDK for iOS
All docsSearch SDK for iOSExamplesDisplay category search results on a map

Display category search results on a map

This example uses the Mapbox Maps SDK for iOS. Add the Maps SDK as a dependency using the Maps SDK installation instructions.

ViewController
import UIKit
import MapboxSearch
class MapboxMapsCategoryResultsViewController: MapsViewController {
let searchEngine = CategorySearchEngine()
// let searchEngine = CategorySearchEngine(accessToken: "<#You can pass access token manually#>")
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
/// Configure RequestOptions to perform search near the Mapbox Office in San Francisco
let requestOptions = SearchOptions(proximity: .sanFrancisco)
searchEngine.search(categoryName: "cafe", options: requestOptions) { response in
do {
let results = try response.get()
self.showAnnotations(results: results)
} catch {
self.showError(error)
}
}
}
}
MapsViewController
import UIKit
import MapboxMaps
import MapboxSearch
import MapboxSearchUI
class MapsSearchViewController: UIViewController {
var searchController = MapboxSearchController()
var mapView: MapView?
var annotationManager: PointAnnotationManager?
override func viewDidLoad() {
super.viewDidLoad()
// Search setup
searchController.delegate = self
let panelController = MapboxPanelController(rootViewController: searchController)
addChild(panelController)
// Map setup
let mapView = MapView(frame: view.bounds)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.mapView = mapView
view.addSubview(mapView)
annotationManager = mapView.annotations.makePointAnnotationManager()
}
func showResults(_ results: [SearchResult]) {
let annotations = results.map { searchResult -> PointAnnotation in
var annotation = PointAnnotation(coordinate: searchResult.coordinate)
annotation.textField = searchResult.name
annotation.textOffset = [0, -2]
annotation.textColor = ColorRepresentable(color: .red)
annotation.image = .default
return annotation
}
annotationManager?.syncAnnotations(annotations)
if case let .point(point) = annotations.first?.feature.geometry {
let options = CameraOptions(center: point.coordinates)
mapView?.mapboxMap.setCamera(to: options)
}
}
}
extension MapsSearchViewController: SearchControllerDelegate {
func categorySearchResultsReceived(results: [SearchResult]) {
showResults(results)
}
func searchResultSelected(_ searchResult: SearchResult) {
showResults([searchResult])
}
func userFavoriteSelected(_ userFavorite: FavoriteRecord) {
showResults([userFavorite])
}
}