'How to get selected place coordinates in google places autocomplete prediction in table view ios swift
i am able to get google places auto complete results in table view using below code. now i am looking for how to get coordinate of selected place of tableview?
func didAutocomplete(with predictions: [GMSAutocompletePrediction]) {
tableData.removeAll()
for predicition in predictions
{
tableData.append(predicition.attributedFullText.string)
}
table1.reloadData()
}
Like if i select the row of table view then below method get invoked and i want to get coordinates of that particular place
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
Solution 1:[1]
From the GMSAutocompletePrediction, you will get a placeID
, which is a textual identifier that uniquely identifies a place. To get a place by ID, call GMSPlacesClient lookUpPlaceID:callback:
, passing a place ID and a callback method.
So you need to declare another global array for saving placesID. Or you can use one array for saving a GMSAutocompletePrediction object; extract the attributedFullText in the cellForRowAtIndexPath for populating the labels and extract the placeID in didSelectRow.
Let say your tableData is an array of GMSAutocompletePrediction object.
var tableData = [GMSAutocompletePrediction]()
Then your didAutocomplete delegate method will be like this
func didAutocomplete(with predictions: [GMSAutocompletePrediction]) {
tableData = predictions
}
And your cellForRowAtIndexPath will be :-
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 */
}
And your didSelectRowAt will be :-
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
}
}
}
You can explore more about it here
Solution 2:[2]
In the last update of Google Maps you can simply get the address
func viewController(_ viewController: GMSAutocompleteViewController, didSelect prediction: GMSAutocompletePrediction) -> Bool {
let suggestedAddress = prediction.attributedFullText.string
return true
}
In this delegate method you can get the full address.
It will concatenate the upper and lower string of the searched address.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |