我正在使用搜索栏来使用 Google 地方信息自动完成功能。但是,当我将搜索栏放在 GMSMapView 顶部时,它不起作用。当我注释掉 loadView() 函数时,它工作得很好。有没有办法通过 Google map 使用地点自动完成功能?
import UIKit
import GoogleMaps
class ViewController: UIViewController {
var resultsViewController: GMSAutocompleteResultsViewController?
var searchController: UISearchController?
var resultView: UITextView?
override func loadView() {
let camera = GMSCameraPosition.cameraWithLatitude(1.285, longitude: 103.848, zoom: 12)
let mapView = GMSMapView.mapWithFrame(.zero, camera: camera)
self.view = mapView
}
override func viewDidLoad() {
super.viewDidLoad()
resultsViewController = GMSAutocompleteResultsViewController()
resultsViewController?.delegate = self
searchController = UISearchController(searchResultsController: resultsViewController)
searchController?.searchResultsUpdater = resultsViewController
let subView = UIView(frame: CGRectMake(0, 65.0, 350.0, 45.0))
subView.addSubview((searchController?.searchBar)!)
self.view.addSubview(subView)
searchController?.searchBar.sizeToFit()
searchController?.hidesNavigationBarDuringPresentation = false
// When UISearchController presents the results view, present it in
// this view controller, not one further up the chain.
self.definesPresentationContext = true
}
}
// Handle the user's selection.
extension ViewController: GMSAutocompleteResultsViewControllerDelegate {
func resultsController(resultsController: GMSAutocompleteResultsViewController,
didAutocompleteWithPlace place: GMSPlace) {
searchController?.active = false
// Do something with the selected place.
print("Place name: ", place.name)
print("Place address: ", place.formattedAddress)
print("Place attributions: ", place.attributions)
}
func resultsController(resultsController: GMSAutocompleteResultsViewController,
didFailAutocompleteWithError error: NSError){
// TODO: handle the error.
print("Error: ", error.description)
}
// Turn the network activity indicator on and off again.
func didRequestAutocompletePredictionsForResultsController(resultsController: GMSAutocompleteResultsViewController) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}
func didUpdateAutocompletePredictionsForResultsController(resultsController: GMSAutocompleteResultsViewController) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
}
以上代码来自https://developers.google.com/maps/documentation/ios-sdk/map和 https://developers.google.com/places/ios-api/autocomplete .我复制了这些用于测试,但仍然无法正常工作。
最佳答案
抱歉,我还没有资格发表评论,但我认为这可以帮助您解决问题。
首先调用 super.loadView() 并且在初始化 GMSMapView 时必须设置帧大小。最后将 mapView 添加到 subview 。
override func loadView() {
super.loadView()
let camera = GMSCameraPosition.cameraWithLatitude(1.285, longitude: 103.848, zoom: 12)
let mapView = GMSMapView.mapWithFrame(self.view.frame, camera: camera)
self.view.addSubview(mapView)
}
关于ios - Swift Google Place Autocomplete 无法与 Google map 配合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38578414/