MKLocalsearchRequest nearby places WITHOUT a naturalLanguageQuery string

1.7k Views Asked by At

Is it all possible to show nearby places with MKLocalSearchRequest without supplying a naturalLanguageQuery?

I'm aware that the typical route is to use foursquare or google for this. I've used both.

3

There are 3 best solutions below

0
On

My strategy is

  1. Get a placemark using geocoder.
  2. Generate a search text which looks fine (which I'm not confident on).
  3. Request MKLocalSearch.

Pseudo code is here.

func placemark() async throws -> CLPlacemark? {
// (1)
    let geocoder: CLGeocoder = .init()
    let location: CLLocation = .init(
        latitude: coordinate.latitude,
        longitude: coordinate.longitude
    )
    return try await geocoder.reverseGeocodeLocation(location).first
}
func findNearbyMapItems() async {
    guard let placemark = placemark else {
        return
    }

// (2)
    let searchText: String = Array(Set([
        placemark.administrativeArea ?? "",
        placemark.subAdministrativeArea ?? "",
        placemark.locality ?? "",
    ])).joined(separator: " ").trimmingCharacters(in: .whitespacesAndNewlines)

// (3)
    let nearbyMeters: CLLocationDistance = 500
    let request = MKLocalSearch.Request()
    request.naturalLanguageQuery = searchText
    request.resultTypes = [.pointOfInterest]
    request.region = MKCoordinateRegion(
        center: center,
        latitudinalMeters: nearbyMeters,
        longitudinalMeters: nearbyMeters
    )

    let response = try await MKLocalSearch(request: request).start()
    return response.mapItems
}

Another solution works only for POI.

func mapItemsNearbyPOIOnSystem(radius: CLLocationDistance = 500) async throws -> [MKMapItem] {
    let request: MKLocalPointsOfInterestRequest = .init(center: coordinate, radius: radius)
    let response = try await MKLocalSearch(request: request).start()
    return response.mapItems
}
0
On

You can achieve it for demo purposes as follows, but I wouldn't recommend using this approach in a production app as it's obviously not scalable.

var nearbyPlaces: [MKMapItem] = []
let params: [String] = ["bar", "shop", "restaurant", "cinema"]
let request = MKLocalSearchRequest()
let span = MKCoordinateSpan(latitudeDelta: CLLocationDegrees(exactly: 1000)!, longitudeDelta: CLLocationDegrees(exactly: 1000)!)
let region = MKCoordinateRegion(center: coord, span: span)
request.region = region

for param in params {

        request.naturalLanguageQuery = param    
        let places = MKLocalSearch(request: request)
        places.start { [unowned self] response, error in
           guard let result = response else { return }
           self.nearbyPlaces.append(contentsOf: result.mapItems)
        }

}
1
On

I have been trying to achieve this for some time, but the closest I have come is using a for loop running multiple queries and adding results to main array. INCREDIBLY inefficient obviously, did you have more success?