我想在使用Swift的Xcode中添加Google地点自动完成功能,以便用户可以搜索一个城市并按Enter键,应用程序将在地图上显示该城市。我正在使用Google地图,因此它必须连接到该地图,我希望将搜索栏放置在导航栏中(就在地图上方)。有人知道好的教程吗?
对于Swift 3:
1- 选择您的podfile并输入:pod 'GooglePlaces'
2- 在appDelegate中添加您的API Key:
GMSPlacesClient.provideAPIKey("YOUR KEY")
(导入GooglePlaces)
3- 在包含谷歌地图的viewController中使用此代码:
// This code snippet demonstrates adding a
// full-screen Autocomplete UI control
import UIKit
import GooglePlaces
class ViewController: UIViewController {
// TODO: Add a button to Main.storyboard to invoke onLaunchClicked.
// Present the Autocomplete view controller when the button is pressed.
@IBAction func onLaunchClicked(sender: UIButton) {
let acController = GMSAutocompleteViewController()
acController.delegate = self
present(acController, animated: true, completion: nil)
}
}
extension ViewController: GMSAutocompleteViewControllerDelegate {
// Handle the user's selection.
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
print("Place name: \(place.name)")
print("Place address: \(place.formattedAddress)")
print("Place attributions: \(place.attributions)")
dismiss(animated: true, completion: nil)
}
func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
// TODO: handle the error.
print("Error: \(error)")
dismiss(animated: true, completion: nil)
}
// User cancelled the operation.
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
print("Autocomplete was cancelled.")
dismiss(animated: true, completion: nil)
}
}
虽然没有详细的教程,但是在Github上有一些资源,人们提供了库和代码示例来实现你所要求的功能。
即使没有适当的教程,你仍然可以查看这些库并理解它们的代码如何工作,以获取灵感,如果想要编写自己的组件。
顺便说一句,Google也有这个页面,但它不是专门针对iOS应用程序的教程,只是一些有关其API如何工作的有用说明:https://developers.google.com/places/documentation/autocomplete#examples
我还创建了一个库,可以在不包括任何第三方框架或库的情况下进行这些简单的请求。您还可以使用该库维护自动完成的缓存。
要使用该库,请按照以下步骤操作:
GoogleApiHelper
导入您的项目中。GoogleApiHelper
GoogleApi.shared.initialiseWithKey("API_KEY")
var input = GInput()
input.keyword = "San francisco"
GoogleApi.shared.callApi(input: input) { (response) in
if let results = response.data as? [GApiResponse.Autocomplete], response.isValidFor(.autocomplete) {
//Enjoy the Autocomplete Api
} else { print(response.error ?? "ERROR") }
}
acController.delegate = self
报错:无法将类型为 'MyController' 的值分配给类型 'GMSAutocompleteViewControllerDelegate?'。 - NEOlineextension ViewController: GMSAutocompleteViewControllerDelegate {
到extension MyController: GMSAutocompleteViewControllerDelegate {
- NEOline