如何在 google 中获取选定的位置坐标,在 table 视图中自动完成预测 ios swift

How to get selected place coordinates in google places autocomplete prediction in table view ios swift

我能够使用以下代码在 table 视图中获得 google 自动完成结果。 现在我正在寻找如何获取 tableview 的 selected 位置的坐标?

 func didAutocomplete(with predictions: [GMSAutocompletePrediction]) {
    tableData.removeAll()

    for predicition in predictions
    {
         tableData.append(predicition.attributedFullText.string)
    }
    table1.reloadData()
}

就像如果我 select table 视图的行然后下面的方法被调用,我想获得那个特定位置的坐标

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

}

从 GMSAutocompletePrediction 中,您将获得一个 placeID,这是一个唯一标识地点的文本标识符。要按 ID 获取地点,请调用 GMSPlacesClient lookUpPlaceID:callback:,传递地点 ID 和回调方法。

因此您需要声明另一个全局数组来保存placesID。或者您可以使用一个数组来保存 GMSAutocompletePrediction 对象;在 cellForRowAtIndexPath 中提取 attributedFullText 以填充标签,并在 didSelectRow 中提取 placeID。

假设您的 tableData 是一个 GMSAutocompletePrediction 对象数组。

var tableData = [GMSAutocompletePrediction]()

那么你的 didAutocomplete 委托方法将是这样的

func didAutocomplete(with predictions: [GMSAutocompletePrediction]) {
    tableData = predictions
}

你的 cellForRowAtIndexPath 将是:-

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    /* Intitialise cell */

    let predictionText = tableData[indexPath.row]attributedFullText.string
    print(“Populate \(predictionText) in your cell labels”)

    /* Return cell */
}

你的 didSelectRowAt 将是:-

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let prediction = tableData[indexPath.row]

    if let placeID = predicition.placeID {
        let placesClient = GMSPlacesClient.shared()
        placesClient.lookUpPlaceID(placeID) { (place, error) in
            if let error = error {
                print("lookup place id query error: \(error.localizedDescription)")
                return
            }

            guard let place = place else {
                print("No place details for \(placeID)")
                return
            }

            let searchedLatitude = place.coordinate.latitude
            let searchedLongitude = place.coordinate.longitude
        }
    }
}

您可以进一步了解它here

在Google地图的最后更新中,您可以简单地获取地址

func viewController(_ viewController: GMSAutocompleteViewController, didSelect prediction: GMSAutocompletePrediction) -> Bool {
    let suggestedAddress = prediction.attributedFullText.string
    return true
}

在这个委托方法中你可以获得完整的地址。

搜索到的地址:

输出:

它将搜索地址的上下字符串拼接起来。