Ansh Vohra
Ansh Vohra

Reputation: 25

Google Places Autocomplete Swift 3

I want to integrate the Google Places Autocomplete API in my project but I am unable to achieve it with the documentation and also couldn't get some solid references for Swift-3. Can anyone please help? Thanks.

Upvotes: 1

Views: 4976

Answers (4)

Shakeel Ahmed
Shakeel Ahmed

Reputation: 6051

Swift 5+ Very easy way to implement it

import UIKit
import GooglePlaces

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    
        // Add a button to trigger the autocomplete
        let button = UIButton(type: .system)
        button.setTitle("Autocomplete", for: .normal)
        button.addTarget(self, action: #selector(presentAutocomplete), for: .touchUpInside)
        button.frame = CGRect(x: 20, y: 50, width: 200, height: 50)
        self.view.addSubview(button)
    }

    @objc func presentAutocomplete() {
        let autocompleteController = GMSAutocompleteViewController()
        autocompleteController.delegate = self
        present(autocompleteController, animated: true, completion: nil)
    }
}

extension ViewController: GMSAutocompleteViewControllerDelegate {
    // Handle the user's selection.
    func viewController(_ viewController: GMSAutocompleteViewController, m didAutocompleteWith place: GMSPlace) {
        print("Place name: \(place.name ?? "")")
        print("Place address: \(place.formattedAddress ?? "")")
        print("Place attributions: \(place.attributions ?? NSAttributedString(string: ""))")
        dismiss(animated: true, completion: nil)
    }

    // Handle the error.
    func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
        print("Error: ", error.localizedDescription)
        dismiss(animated: true, completion: nil)
    }

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

    // Turn the network activity indicator on and off again.
    func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
    }

    func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
    }
}

Upvotes: 0

Kuldeep Tanwar
Kuldeep Tanwar

Reputation: 3526

I also created an simple library just to avoid various third party library and google framework for simple requests.

To make a Google api request like Autocomplete, ReverseGeo, Place info or Draw path you can simply use these steps :-

step-1 Import GoogleApiHelper into your project.

step-2 Initialise GoogleApiHelper

GoogleApi.shared.initialiseWithKey("API_KEY")

step-3 Call the methods

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

Upvotes: 0

Vasily  Bodnarchuk
Vasily Bodnarchuk

Reputation: 25304

Details

Swift 4, xCode 9

Solution

Usual http request. More details: https://developers.google.com/places/ios-api/autocomplete

Full sample

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

Network

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

Extensions

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

Results

enter image description here

Upvotes: 2

Wide Angle Technology
Wide Angle Technology

Reputation: 1222

You need to install google place SDK in your project through pods first. pod 'GooglePlacePicker' you can use this code for install googlePlaces through pods.

Upvotes: 0

Related Questions