create a map search function in swift

To create a map search function in Swift, you can use MapKit framework provided by Apple. Here is the step-by-step guide to create a map search functionality:

Step 1: Add MapKit framework

  • Open your Xcode project.
  • Select your project file from the project navigator on the left pane.
  • Select your target and go to the "General" tab.
  • Click the "+" button under the "Frameworks, Libraries, and Embedded Content" section.
  • Select "MapKit.framework" from the list and click "Add".

Step 2: Add a map view to your user interface

  • Open the storyboard or the xib file where you want to add the map view.
  • Drag and drop a "Map Kit View" from the object library to your view controller.
  • Pin the map view to the edges of the superview.
  • Create an IBOutlet for the map view in your view controller.

Step 3: Implement search functionality

  • Conform to UISearchBarDelegate protocol in your view controller.
  • Add a search bar to your user interface.
  • Implement searchBarSearchButtonClicked(_:) method, which gets called when user taps the search button on the keyboard.
  • Create a MKLocalSearch object with a search request based on the user's input text.
  • Call start(completionHandler:) method on the MKLocalSearch object to perform the search in the map.
  • In the completion handler of start(completionHandler:) method, get the list of MKMapItem objects which match the search request.
  • Add the first MKMapItem object to the map view using addAnnotation(_:) method.
  • Set the region property of the map view to the region containing the searched location.

Here's a code snippet that shows how to implement the above steps:

main.swift
import MapKit

class MyViewController: UIViewController, UISearchBarDelegate {
    
    @IBOutlet weak var mapView: MKMapView!
    let searchCompleter = MKLocalSearchCompleter()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        searchCompleter.delegate = self
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        let searchRequest = MKLocalSearch.Request()
        searchRequest.naturalLanguageQuery = searchBar.text
        let localSearch = MKLocalSearch(request: searchRequest)
        localSearch.start { [weak self] (response, error) in
            guard let mapItem = response?.mapItems.first else { return }
            self?.mapView.addAnnotation(mapItem)
            self?.mapView.setRegion(MKCoordinateRegion(center: mapItem.placemark.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)), animated: true)
        }
    }
}

extension MyViewController: MKLocalSearchCompleterDelegate {
    
    func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
        // Handle if you want to show autocomplete suggestions
    }
    
    func completer(_ completer: MKLocalSearchCompleter, didFailWithError error: Error) {
        print(error.localizedDescription)
    }
}
1270 chars
35 lines

This code snippet uses UISearchBar to get user's input and MKLocalSearch to perform the search. Once the search is complete, it adds the first result to the MKMapView. You can also implement the MKLocalSearchCompleterDelegate to show autocomplete suggestions to the user while typing.

gistlibby LogSnag