Search using MapKit in SwiftUI

Sai Durga Mahesh
Geek Culture
Published in
1 min readJul 25, 2022
Photo by Z on Unsplash

Searching for places is an interesting feature that we might need in our applications. Let’s develop this feature with SwiftUI.

First, Let us create a view model with a class that confirms to Observable object. This class has searchResults variable which publishes the search results. The LocationManager confirms to ‘MKLocalSearchCompleterDelegate’ which provides the search results through ‘completerDidUpdateResults’.

The getDistance method is used to calculate distance between current location and search result.

We can further select result types and choose whether to include point of interests or not.

self.searchCompleter.resultTypes = [.address]self.searchCompleter.pointOfInterestFilter = .includingAllself.publisher = $search.receive(on: RunLoop.main).sink(receiveValue: { [weak self] (str) inself?.searchCompleter.queryFragment = str})

Now, Let us create a simple List that shows the above results and calculate distance of result from current location.

The reverseUpdate() in the above view requires a dedicated post in which we will fetch the details of location from coordinates and vice versa.

Thanks for reading :))

--

--

Sai Durga Mahesh
Geek Culture

Using Data Science to provide better solutions to real word problems