在Swift 3中单击textField时,在tableView上搜索Google Places?

时间:2017-08-24 06:22:26

标签: swift3 google-places

当我点击Google Places并希望在textField下方显示结果时,如何搜索textField。我使用的是Swift 3.0版本。有人可以帮助我

3 个答案:

答案 0 :(得分:7)

首先,您需要在项目中安装GooglePlaces SDK。然后你可以参考下面的代码。

Swift 3中的

在AppDelegate中

import UIKit
import CoreData
import GoogleMaps
import GooglePlacePicker

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions 
launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    func setUpGoogleMaps()
    return true
}

func setUpGoogleMaps() {
    let googleMapsApiKey = "AIzaSyA-kiOBvrR9CNztqutwmKaSLyXIid93K0E"
    GMSServices.provideAPIKey(googleMapsApiKey)
    GMSPlacesClient.provideAPIKey("AIzaSyA-kiOBvrR9CNztqutwmKaSLyXIid93K0E")
}

在具有textField

的ViewController中
import UIKit
import GooglePlaces
import GoogleMaps
import GooglePlacePicker

class HotelVC: UIViewController, GMSMapViewDelegate, UITextFieldDelegate {

@IBOutlet weak var YourTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    self.YourTextField.delegate = self

}

func textFieldDidBeginEditing(_ textField: UITextField) {
    let acController = GMSAutocompleteViewController()
    acController.delegate = self
    self.present(acController, animated: true, completion: nil)
  }
}


extension viewController: GMSAutocompleteViewControllerDelegate {

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

    print("Place name: \(place.name)")
    print("Place address: \(place.formattedAddress ?? "null")")
    self.YourTextField.text = place.formattedAddress
    print("Place attributions: \(String(describing: place.attributions))")

    self.dismiss(animated: true, completion: nil)
}
func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
    // TODO: handle the error.
    //        print("Error: \(error.description)")
    self.dismiss(animated: true, completion: nil)
}

// User canceled the operation.
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
    print("Autocomplete was cancelled.")
    self.dismiss(animated: true, completion: nil)
    }
}

答案 1 :(得分:1)

您将从所选位置获取位置。试试这段代码。

public func viewController(viewController: GMSAutocompleteViewController, didAutocompleteWithPlace place: GMSPlace) {
var lat = place.coordinate.latitude
var lon = place.coordinate.longitude
print("lat lon",lat,lon)

}

答案 2 :(得分:0)

您可以使用Google Places API。它可以帮助您轻松找到地方,也可以通过textField激活它。

以下是链接https://developers.google.com/places/ios-api/autocomplete