Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/97.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在GMSAutocomplete中使用文本字段而不是搜索栏,方法相同_Ios_Swift_Google Maps_Autocomplete_Google Places Api - Fatal编程技术网

Ios 在GMSAutocomplete中使用文本字段而不是搜索栏,方法相同

Ios 在GMSAutocomplete中使用文本字段而不是搜索栏,方法相同,ios,swift,google-maps,autocomplete,google-places-api,Ios,Swift,Google Maps,Autocomplete,Google Places Api,我正在使用google Place Autocomplete API,我需要添加UITextField,而不是具有相同功能的UISearchBar。这是我从UISearchBar获得的工作代码。如果有人帮我从任何搜索关键字中获取地址数组,我将自己添加textfield和tableview。比如从字符串(关键字)到数组(预测位置) 如果您使用UITextField和自己的UITableView来代替UISearchController,那么直接使用该类就更容易了 GoogleMaps Cocoap

我正在使用google Place Autocomplete API,我需要添加UITextField,而不是具有相同功能的UISearchBar。这是我从UISearchBar获得的工作代码。如果有人帮我从任何搜索关键字中获取地址数组,我将自己添加textfield和tableview。比如从字符串(关键字)到数组(预测位置)


如果您使用UITextField和自己的UITableView来代替UISearchController,那么直接使用该类就更容易了

GoogleMaps Cocoapod的一个代码示例展示了如何做到这一点。如果您已经安装了pod,请在项目的
Pods/GoogleMaps/googlemapssdkddemos/SDKDemos/PlacesSamples
目录中查找文件
SDKDemoAutocompleteWithTextFieldController
,或者运行
pod try GoogleMaps
下载示例。

集成您的GPA(Google Places API)。POD文件包括:

pod 'GooglePlaces'
pod 'GooglePlacePicker'
pod 'GoogleMaps'
首先,提供AppDelegate.swift的密钥

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        GMSPlacesClient.provideAPIKey("Your KEY")
        return true
    }
首先,获取一个文本字段和一个表视图。然后将这些行添加到ViewController.swift文件中,钩住textField和tableView,最后运行它

    import UIKit
    import GooglePlaces

    class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{

    @IBOutlet weak var PlaceTextField: UITextField!

    @IBOutlet weak var tableView: UITableView!

    var tableData=[String]()

    var fetcher: GMSAutocompleteFetcher?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.lightGray
        self.edgesForExtendedLayout = []

        // Set bounds to inner-west Sydney Australia.
        let neBoundsCorner = CLLocationCoordinate2D(latitude: -33.843366,
                                                    longitude: 151.134002)
        let swBoundsCorner = CLLocationCoordinate2D(latitude: -33.875725,
                                                    longitude: 151.200349)
        let bounds = GMSCoordinateBounds(coordinate: neBoundsCorner,
                                         coordinate: swBoundsCorner)

        // Set up the autocomplete filter.
        let filter = GMSAutocompleteFilter()
        filter.type = .establishment

        // Create the fetcher.
        fetcher = GMSAutocompleteFetcher(bounds: bounds, filter: filter)
        fetcher?.delegate = self as! GMSAutocompleteFetcherDelegate

        PlaceTextField.addTarget(self, action: #selector(ViewController.textFieldDidChanged(_:)), for: UIControlEvents.editingChanged)

        tableView.delegate = self
        tableView.dataSource = self

        tableView.reloadData()
    }

    // MARK: -UITextField Action

    @objc func textFieldDidChanged(_ textField:UITextField ){
        print(PlaceTextField.text!)
        fetcher?.sourceTextHasChanged(PlaceTextField.text!)
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableData.count
    }

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

        var section = indexPath.section

        var row = indexPath.row

        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier:"addCategoryCell")

        cell.selectionStyle =  UITableViewCellSelectionStyle.none
        cell.backgroundColor = UIColor.clear
        cell.contentView.backgroundColor = UIColor.clear
        cell.textLabel?.textAlignment = NSTextAlignment.left
        cell.textLabel?.textColor = UIColor.black
        cell.textLabel?.font = UIFont.systemFont(ofSize: 14.0)

        cell.textLabel?.text = tableData[indexPath.row]

        return cell
    }
}

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

        for prediction in predictions {

            tableData.append(prediction.attributedPrimaryText.string)

            //print("\n",prediction.attributedFullText.string)
            //print("\n",prediction.attributedPrimaryText.string)
            //print("\n********")
        }

        tableView.reloadData()
    }

    func didFailAutocompleteWithError(_ error: Error) {
        print(error.localizedDescription)
    }
}

//在视图控制器中有TextField和TableView设置

import UIKit
import GooglePlaces

class TableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var txtField: UITextField!
    @IBOutlet weak var table1: UITableView!

    var tableData = [String]()

    var fetcher: GMSAutocompleteFetcher?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white
        self.edgesForExtendedLayout = []

        let nsBoundsCorner = CLLocationCoordinate2D(latitude: 20.5937, longitude: 78.9629)

        let bounds = GMSCoordinateBounds(coordinate: nsBoundsCorner, coordinate: nsBoundsCorner)

        let filter = GMSAutocompleteFilter()
        filter.type = .establishment

        fetcher  = GMSAutocompleteFetcher(bounds: bounds, filter: filter)
        fetcher?.delegate = self

        txtField?.addTarget(self, action: #selector(textFieldDidChange(textField:)),for: .editingChanged)

        table1.delegate = self
        table1.dataSource = self

        self.table1.reloadData()


        // Do any additional setup after loading the view.
    }

    @objc func textFieldDidChange(textField: UITextField) {
            fetcher?.sourceTextHasChanged(txtField.text!)
        }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return tableData.count
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var section = indexPath.section
        var row = indexPath.row

        let cell1 : UITableViewCell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell1")

        cell1.selectionStyle = UITableViewCellSelectionStyle.none
        cell1.backgroundColor = UIColor.clear
        cell1.contentView.backgroundColor = UIColor.clear
        cell1.textLabel?.textAlignment = NSTextAlignment.left
        cell1.textLabel?.textColor = UIColor.black
        cell1.textLabel?.font = UIFont.systemFont(ofSize: 14.0)

        cell1.textLabel?.text = tableData[indexPath.row]
        return cell1
    }



//    extension TableViewController: GMSAutocompleteFetcherDelegate {
//
//        func didAutocompleteWithPredictions(predictions: [GMSAutocompletePrediction]) {
//
//            tableData.removeAll()
//
//            for prediction in predictions {
//
//                tableData.append(prediction.attributedPrimaryText.string)
//
//            }
//
//            table1.reloadData()
//        }
//
//    }



    @IBAction func textField1(_ sender: Any) {
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension TableViewController: GMSAutocompleteFetcherDelegate {


    func didAutocomplete(with predictions: [GMSAutocompletePrediction]) {

        tableData.removeAll()

        for prediction in predictions{

            tableData.append(prediction.attributedFullText.string)

        }
        table1.reloadData()
    }

    func didFailAutocompleteWithError(_ error: Error) {
        print(error.localizedDescription)
    }



}
//还可以设置应用程序代理

import UIKit
import GooglePlaces
import GoogleMaps
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

////        [GMSPlacesClient provideAPIKey:...]
//        [GMSPlacesClient .provideAPIKey("xxxxxxxxxxxxxxxxxxxxxx")]

        GMSPlacesClient.provideAPIKey("xxxxxxx")
        GMSServices.provideAPIKey("xxxxxxxxxx")

        return true
    }
}

如何从prediction object获取所选地点的坐标?我刚刚实现了这一点,并尝试在加拿大搜索特定地址,但它不起作用。它只显示机场名称或餐厅名称等地名,但不显示具体地址。我如何在这里用您的代码专门填充地址?
import UIKit
import GooglePlaces
import GoogleMaps
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

////        [GMSPlacesClient provideAPIKey:...]
//        [GMSPlacesClient .provideAPIKey("xxxxxxxxxxxxxxxxxxxxxx")]

        GMSPlacesClient.provideAPIKey("xxxxxxx")
        GMSServices.provideAPIKey("xxxxxxxxxx")

        return true
    }
}