Example of SwiftUI implementation of MKLocalSearch.Request()

How do I implement MapKit MKLocalSearch.Request() in SwiftUI?

Answered by enterpriser1701 in 678725022

Thank you. I was able to figure this out. I wanted to be able to make the MapView open to a specific country/state and zoom to the full extent of the selected country/state. In my example below, I am using "Mexico" as the search parameter. This is where you would pass in your parameter. There are somethings to consider when passing in your search string parameter, Georgia for example is a US State and a Country. I've constructed my search strings to be the name of the county/state followed by the 2 letter country code. "Georgia, GE" for the country, "Georgia, US".

import MapKit
import SwiftUI

struct MapView: UIViewRepresentable {

    @State private var searchString = String()

    class Coordinator: NSObject, MKMapViewDelegate {

        var parent: MapView

        init(_ parent: MapView) {

            self.parent = parent

        }


        func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {

            print("Center Coordinate: \(mapView.centerCoordinate)")

        }

    }


    func makeCoordinator() -> Coordinator {

        Coordinator(self)

    }


    func makeUIView(context: UIViewRepresentableContext<MapView>) -> MKMapView {

        let mapView = MKMapView()



        let searchRequest = MKLocalSearch.Request()

        searchRequest.naturalLanguageQuery = "Mexico" // This is where you can pass in you search string parameter.



        let search = MKLocalSearch(request: searchRequest)



        search.start { response, error in

            guard let response = response else {

                print("Error: \(error?.localizedDescription ?? "Unknown error").")

                return

            }

            mapView.setRegion(response.boundingRegion, animated: true) // .boundingRegion is what opens the map to the extent of the searched country/state.

        }

        return mapView

    }


    func updateUIView(_ uiView: MKMapView, context: Context) {

    }

}


struct MapView_Previews: PreviewProvider {

    static var previews: some View {

        MapView()

    }

}

Performing an MKLocalSearch is not really different in a SwiftUI app compared to a non-SwiftUI app. SwiftUI is the framework that you use to compose your user interface. The remaining app logic is still implemented in much the same way regardless if you are using SwiftUI or UIKit for your UI.

For example, if you want your MKLocalSearch to be triggered in response to a button tap, you can simply let your button action closure call out to a method where you set up and execute the MKLocalSearch.Request.

Depending on what you want to do with the result, you could for example make the completion handler of the MKLocalSearch update your respective object, which could trigger the view to update and display the results.

For more information and a code example on how you create and execute an MKLocalSearch, see the documentation (https://developer.apple.com/documentation/mapkit/mklocalsearch/request).

Accepted Answer

Thank you. I was able to figure this out. I wanted to be able to make the MapView open to a specific country/state and zoom to the full extent of the selected country/state. In my example below, I am using "Mexico" as the search parameter. This is where you would pass in your parameter. There are somethings to consider when passing in your search string parameter, Georgia for example is a US State and a Country. I've constructed my search strings to be the name of the county/state followed by the 2 letter country code. "Georgia, GE" for the country, "Georgia, US".

import MapKit
import SwiftUI

struct MapView: UIViewRepresentable {

    @State private var searchString = String()

    class Coordinator: NSObject, MKMapViewDelegate {

        var parent: MapView

        init(_ parent: MapView) {

            self.parent = parent

        }


        func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {

            print("Center Coordinate: \(mapView.centerCoordinate)")

        }

    }


    func makeCoordinator() -> Coordinator {

        Coordinator(self)

    }


    func makeUIView(context: UIViewRepresentableContext<MapView>) -> MKMapView {

        let mapView = MKMapView()



        let searchRequest = MKLocalSearch.Request()

        searchRequest.naturalLanguageQuery = "Mexico" // This is where you can pass in you search string parameter.



        let search = MKLocalSearch(request: searchRequest)



        search.start { response, error in

            guard let response = response else {

                print("Error: \(error?.localizedDescription ?? "Unknown error").")

                return

            }

            mapView.setRegion(response.boundingRegion, animated: true) // .boundingRegion is what opens the map to the extent of the searched country/state.

        }

        return mapView

    }


    func updateUIView(_ uiView: MKMapView, context: Context) {

    }

}


struct MapView_Previews: PreviewProvider {

    static var previews: some View {

        MapView()

    }

}
Example of SwiftUI implementation of MKLocalSearch.Request()
 
 
Q