谷歌地方自动完成Swift 3

时间:2017-07-09 12:49:34

标签: ios swift3 google-places-api google-maps-sdk-ios

我想在我的项目中集成Google Places Autocomplete API,但我无法通过文档实现它,也无法获得Swift-3的一些可靠参考。有人可以帮忙吗?感谢。

3 个答案:

答案 0 :(得分:2)

详细

Swift 4,xCode 9

解决方案

通常的http请求。更多详情:https://developers.google.com/places/ios-api/autocomplete

完整样本

  

PodFile

target 'stackoverflow-44996568' do
    use_frameworks!
    pod 'Alamofire'
    pod 'ObjectMapper'      
end
  

GoogleAutocompleteJSONModel

import ObjectMapper

class GoogleAutocompleteJSONModel: Mappable, CustomStringConvertible {

    public fileprivate(set) var placeId: String?
    public fileprivate(set) var reference: String?
    public fileprivate(set) var title: String?

    required convenience init?(map: Map) {
        self.init()
    }

    func mapping(map: Map) {

        title                       <- map["description"]
        placeId                     <- map["place_id"]
        reference                   <- map["reference"]
    }

    var description: String {
        return "\(toJSON())"
    }
}
  

网络

import Alamofire
import ObjectMapper

class Network {

    class GoogleAPI {
        class Map {

            class var googleApiKey: String {
                return "YOUR_KEY"
            }

            class func autocomplete(request: String) {
                let url = "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=\(request)&components=country:us&key=\(googleApiKey)"
                Alamofire.request(url)
                    .responseJSON { response in
                        if let json = response.result.value as? [String: Any] {
                            //print("JSON: \(json)")
                            let places = Array<GoogleAutocompleteJSONModel>(json: json["predictions"])
                            let autocomplete = places.flatMap{ $0.title}
                            print("!!!! \(autocomplete)")
                        }
                }
            }
        }
    }
}
  

扩展

import Foundation

extension Array where Element: Mappable {

    init(json: Any?) {
        self.init()

        var result = [Element]()
        if let array = json as? [[String: Any]] {
            for item in array {
                if let profile = Element(JSON: item) {
                    result.append(profile)
                }
            }
        }
        self = result
    }
}
  

的ViewController

import UIKit

class ViewController: UIViewController {

    weak var searchBar: UISearchBar!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let searchBar = UISearchBar(frame: CGRect(origin: CGPoint(x: 0, y: 20), size: CGSize(width: UIScreen.main.bounds.width, height: 40)))
        searchBar.delegate = self
        view.addSubview(searchBar)
        self.searchBar = searchBar
    }
}

extension ViewController: UISearchBarDelegate {
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        Network.GoogleAPI.Map.autocomplete(request: searchText)
    }
}

结果

enter image description here

答案 1 :(得分:0)

您需要先通过pod在项目中安装google place SDK。 pod 'GooglePlacePicker'您可以使用此代码通过pod安装googlePlaces。

答案 2 :(得分:0)

我还创建了一个简单的库,只是为了避免针对简单请求的各种第三方库和google框架。

要发出诸如AutocompleteReverseGeoPlace信息或Draw路径之类的Google api请求,您只需使用以下步骤:-

步骤1将GoogleApiHelper导入项目。

步骤2初始化GoogleApiHelper

GoogleApi.shared.initialiseWithKey("API_KEY")

步骤3调用方法

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") }
}

You can find the library here

enter image description here