swiftgoogle-places-apigoogle-places-autocompleteclgeocoder

Core Location geocoding from Google Places address does not work for Italian cities


I am using Google Places API for searching city names. In my view controller I am conforming to GMSAutocompleteResultsViewControllerDelegate:

func resultsController(_ resultsController: GMSAutocompleteResultsViewController,
                       didSelect prediction: GMSAutocompletePrediction) -> Bool {
    let geocoder = CLGeocoder()
    geocoder.geocodeAddressString(prediction.attributedFullText.string) { (placemark, error) in }
    return true
}

I need CLGeocoder in order to extract the CLLocation from the address string I am getting from Google Places API. This works perfectly for most cases except for Italian cities. Geocoder cannot handle the full address (example from Google Places result: Roma, Metropolitan City of Rome, Italy). What happens is you get a CLGeocoder error.

What I tried:

I tried only extracting the city + country names. This works for Italian cities but doesn't work for cities with the same name: New York, NY and New York, IA etc (you get wrong results).

Another solution would be to try with the prediction.attributedFullText.string and if it doesn't work retry with the above workaround.

Anyone's had the same issue or has an idea how to handle it more gracefully? I know it is kind of an edge case but I believe Google Places should've thought about the results working with CLGeocoder.


Solution

  • you can easily get the coordinates and formattedAddress using the callback function.

    func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
        print("Place name: \(String(describing: place.name))")
        print("Place address: \(String(describing: place.formattedAddress))")
        print("Place attributions: \(String(describing: place.attributions))")
        dismiss(animated: true, completion: nil)
    
        // get the selected coordinates and address like this
        let yourCordniates = place.coordinate
        let yourAddress = place.formattedAddress ?? ""
    
    
    }