0

我有一个 GMSAutocompleteViewController 在按下按钮后出现。继承人的代码:

 let autocompleteController = GMSAutocompleteViewController()
    autocompleteController.delegate = self

    let fields: GMSPlaceField = GMSPlaceField(rawValue: UInt(GMSPlaceField.name.rawValue) |
        UInt(GMSPlaceField.placeID.rawValue))!
    autocompleteController.placeFields = fields

    let filter = GMSAutocompleteFilter()
    filter.type = .geocode
    filter.country = "US"
    autocompleteController.autocompleteFilter = filter

    present(autocompleteController, animated: true, completion: nil)

当用户搜索时,视图控制器的结果如下所示:

在此处输入图像描述

并使用此代码,我可以返回该地点的名称,以及格式化的地址和属性:

func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
    print("Place name: \(place.name)")
    print("Formatted address: \(place.formattedAddress)")
    print("Place attributions: \(place.attributions)")
    dismiss(animated: true, completion: nil)
}

打印出来-> 地名:Tremosine 格式化地址:nil 地点归属:nil

我要返回的是屏幕截图中的第二行,上面写着“意大利布雷西亚省”,以便我可以将其存储在我的后端。关于如何获取该文本的任何想法?

4

2 回答 2

3

我找到了该问题的解决方案,并且为此使用了单例类。

class GoogleLocation {

    var lat, lng: Double?
    var city, state, country, name: String?

    func extractFromGooglePlcae(place: GMSPlace) -> GoogleLocation {
        self.lat = place.coordinate.latitude
        self.lng = place.coordinate.longitude
        self.city = place.name!
        self.state = place.addressComponents?.first(where: { $0.type == "administrative_area_level_1" })?.name
        self.country = place.addressComponents?.first(where: { $0.type == "country" })?.name
        self.name = self.getFullName()


        return self
    }

    private func getFullName() -> String {
        //return "\(String(describing: self.city)), \(String(describing: self.state)), \(String(describing: self.country))"
        return self.city! + ", " + self.state! + ", " + self.country!
    }
}

在 viewController 中,您应该传递 place 对象。

 func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {

          googleLocation = GoogleLocation().extractFromGooglePlcae(place: place)

        }

如果您对此有任何问题,请告诉我。 谢谢

于 2019-08-07T12:15:40.820 回答
0

您必须使用 addressComponents 值来获取格式化的地址。

let autocompleteController = GMSAutocompleteViewController()
autocompleteController.delegate = self
let fields: GMSPlaceField = GMSPlaceField(rawValue: 
  UInt(GMSPlaceField.formattedAddress.rawValue) |
            UInt(GMSPlaceField.addressComponents.rawValue))!
autocompleteController.placeFields = fields

let filter = GMSAutocompleteFilter()
filter.type = .geocode
filter.country = "US"
autocompleteController.autocompleteFilter = filter

present(autocompleteController, animated: true, completion: nil)
于 2021-01-07T12:27:31.340 回答