swiftgeocodingcllocationgeocode

How to use a swift geocoder on a venue/business name to get address


I am trying to get the address for a venue/business name. With the venue name I have the city and state as well, but it is successful less than 10% of the time. The problem seems to be with finding the location and not deciphering the address.

Example Input: "Jazz Kitchen Indianapolis,Indiana"

Typical Output: "No location found"

Thanks!

geocoder.geocodeAddressString(newSearch) { (placemarks, error) in
                    if let error = error {
                        print("Geocoding error: \(error.localizedDescription)")
                        geoError = true
                    }
                    if let placemark = placemarks?.first {
                        if let address = placemark.location?.coordinate {
                            print("Address: \(address)")
                            let webLoc = CLLocation(latitude: address.latitude, longitude: address.longitude)
                            uploadLoc(geoLoc: webLoc)
                        } else {
                            print("No address found")
                            geoError = true
                        }
                    } else {
                        print("No location found")
                        geoError = true
                    }
            }

Solution

  • For the example request in your question, using MKLocalSearch works better than CLGeocoder.

    The following code:

    import MapKit
    
    let req = MKLocalSearch.Request()
    req.naturalLanguageQuery = "Jazz Kitchen Indianapolis,Indiana"
    let srch = MKLocalSearch(request: req)
    srch.start { resp, error in
        if let resp {
            print(resp.mapItems)
        } else if let error {
            print(error)
        } else {
            print("nothing")
        }
    }
    

    gives the following result:

    [<MKMapItem: 0x600002df8d00> {
        isCurrentLocation = 0;
        name = "The Jazz Kitchen";
        phoneNumber = "<redacted for SO>";
        placemark = "The Jazz Kitchen, 5377 N College Ave, Indianapolis, IN 46220, United States @ <+39.85087740,-86.14554230> +/- 0.00m, region CLCircularRegion (identifier:'<+39.85087741,-86.14554230> radius 141.17', center:<+39.85087741,-86.14554230>, radius:141.17m)";
        timeZone = "America/Indiana/Indianapolis (EST) offset -18000";
        url = "http://www.thejazzkitchen.com";
    }]