Google Places address entry for iOS (Swift)

Overview

GooglePlacesAutocomplete

Build Status CocoaPod

A simple Google Places API autocompleting address entry view for iOS devices.

There are already a couple of solutions out there for this. GooglePlacesAutocomplete is different because it is 100% Swift, and aims to provide the simplest possible method of entering validated, autocompleted addresses.

No attempt has been made to integrate MapKit since displaying Google Places on a non-Google map is against their terms of service.


Requirements

  • iOS 7.0+
  • XCode 7.0+ / Swift 2.0

Installation

Embedded frameworks require a minimum deployment target of iOS 8.

To use GooglePlacesAutocomplete with a project targeting iOS 7, you must include the source files directly in your project. See the 'manual installation' section for instructions.

CocoaPods

CocoaPods is a dependency manager for Cocoa projects.

CocoaPods 0.36 adds supports for Swift and embedded frameworks. You can install it with the following command:

$ gem install cocoapods

To integrate GooglePlacesAutocomplete into your Xcode project using CocoaPods, specify it in your Podfile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'

pod 'GooglePlacesAutocomplete'

Then, run the following command:

$ pod install

Manual

Simply copy GooglePlacesAutocomplete.swift and GooglePlacesAutocomplete.xib to your project.

Note: Don't forget to add the PoweredByGoogle image to your xcassets.

Usage

Use the Google Developers Console to enabled the 'Google Places API Web Service' and create a 'Server' API key credential. In both cases do not use the iOS options.

import GooglePlacesAutocomplete // Not required when including source files directly in project

let gpaViewController = GooglePlacesAutocomplete(
  apiKey: "[YOUR GOOGLE PLACES API KEY]",
  placeType: .Address
)

gpaViewController.placeDelegate = self // Conforms to GooglePlacesAutocompleteDelegate

presentViewController(gpaViewController, animated: true, completion: nil)

GooglePlacesAutocompleteDelegate supports three methods:

  • placesFound(places: [Place]): Invoked whenever the Google Places API is called
  • placeSelected(place: Place): Invoked when a new place is selected
  • placeViewClosed(): Invoked when the view is closed

Here's a complete example.

Place Details

From Google's documentation: "you can request more details about a particular establishment or point of interest by initiating a Place Details request. A Place Details request returns more comprehensive information about the indicated place such as its complete address, phone number, user rating and reviews."

place.getDetails { details in
  println(details.name)       // Convenience accessor for name
  println(details.latitude)   // Convenience accessor for latitude
  println(details.longitude)  // Convenience accessor for longitude
  println(details.raw)        // Complete JSON data (see below)
}

/*
  [
    status: OK,
    result: {
      "address_components" = (
        {
          "long_name" = Paris;
          "short_name" = Paris;
          types = (
            locality,
            political
          );
        },
        ...
      );
      geometry = {
        location = {
          lat = "48.856614";
          lng = "2.3522219";
        };
  ...
*/

See the documentation for full response details.

Location Biasing

The Place Autocomplete API supports biasing results to a specified circle by passing a location and a radius parameter. This instructs the service to prefer showing results within that circle. Results outside of the defined area may still be displayed.

gpaViewController.locationBias = LocationBias(latitude: 48.8534275, longitude: 2.3582787999999937, radius: 1000)

Styling

The UINavigationController appearance can also easily be changed, for example:

gpaViewController.navigationBar.barStyle = UIBarStyle.Black
gpaViewController.navigationBar.translucent = false
gpaViewController.navigationBar.barTintColor = UIColor(red: 0.11, green: 0.27, blue: 0.53, alpha: 1.0)
gpaViewController.navigationBar.tintColor = UIColor.whiteColor()
gpaViewController.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Zapfino", size: 16.0)!]

Also, to change the contents of the title bar:

gpaViewController.navigationItem.title = "Enter City"
gpaViewController.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: gpaViewController, action: "close")

Contributing

  1. Fork it ( https://github.com/watsonbox/ios-google-places-autocomplete/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request
Comments
  • GooglePlaces API Error: REQUEST_DENIED error?

    GooglePlaces API Error: REQUEST_DENIED error?

    Hello, I am getting this error while trying to search any address in search field. Can you suggest what i might be doing wrong? I have only added my api key in the existing code.

    opened by AbhiVashistha 6
  • Swift 2.0

    Swift 2.0

    Swift 2.0 - should all compile and test ok.

    • Cocoapods re-integrated using v0.39.0 and use_frameworks!
    • .travis.yml changed to use xcode7 image
    • OHHTTPStubs updated to v4.3
    • Test targets and build settings generally fiddled with and fixed.
    • GooglePlacesRequestHelpers has some stray bits of error passing from my fork which I've left in.
    opened by samscam 4
  • Close Button not working?

    Close Button not working?

    On click of close button, the same view is loaded again. I have called this view controller as a modal segue from another view controller. How can I go back to previous view controller on click of close button? Thanks!

    opened by AbhiVashistha 4
  • Using current location with google places autocomplete

    Using current location with google places autocomplete

    Hey! Thanks a lot for your contribution. I wanted to ask 2 things:

    1. Is there a way I can insert an option called "use current location -

      "? which shows the user current physical address as an element in the table before all other results? Of course the device would have to ask permission from the user to know his location

    2. Is there a way the list of results received in the table could be organized by the ones that are closest to the current location of the user? (again, with location permission)

    Looking forward to your reply, thanks again

    opened by rosothefox 3
  • Potential Feature: Use Places Details API to get additional meta-data for a place

    Potential Feature: Use Places Details API to get additional meta-data for a place

    Wanted to check in and see if you thought this was a worthy feature for this.

    I would love to get the lat and long of the place as well as a few other points of Meta Data. However, the Places Autocomplete API does not provide that. I would make a call to the Places Details API for that.

    Would you accept a pull request with that feature that lets you turn that "Details" data on and off?

    enhancement 
    opened by h0h0h0 3
  • Closing the xib view

    Closing the xib view

    Thank you for reading this post. Please note - I am new to programming.

    I am having the following issue: http://stackoverflow.com/questions/28521605/having-issues-with-nib-from-ios-google-places-autocomplete

    The xib file is loaded in a Viewcontroller under the ViewDidLoad method, I am attempting to get back to the parent ViewController, from which I came to the autocomplete ViewController. However, everytime I close the the autocomplete.xib view it reloads again because the ViewDidLoad tells it to do so in the example code kindly provided.

    I don't understand how to:

    1. Click on the button so it redirects back to the parent view.
    2. Make a selection on the cell so it navigates the user to the parent view.

    Again - my apologies if this is a basic question, as mentioned - I'm new to programming.

    opened by Rogog 3
  • To import this code to new project it shows error.

    To import this code to new project it shows error.

    gpaViewController.placeDelegate = self

    In this line i have error "type viewcontroller does not conform to protocol googleplacesautocompletedelegate".

    How to fix it and what is the solution.

    opened by Saravana181187 3
  • Have to use pod 'GooglePlacesAutocomplete', :head in my podfile to get the new versions

    Have to use pod 'GooglePlacesAutocomplete', :head in my podfile to get the new versions

    The podspec version of the pod is still 0.1 and I had to add :head to my GooglePlacesAutocomplete pod file entry to get the fixed places id and the paces detail functionality.

    opened by thekie 2
  • Separate UI from service layer

    Separate UI from service layer

    I've had a fork on the go (samscam/ios_google_places_autocomplete) for a while where I've done quite a bit of work on it. Using it in production on Knocker.

    I'll clean up what I've done and submit a bunch of pull requests for you for the smaller things, but the big one is that I needed to separate out the UI from the service layer so it can be used in programatic contexts. I've tried to do it in as non-breaking a way I could but would love to go a bit deeper. Would you be game for that?

    opened by samscam 1
  • placeViewClosed keeps the view to reappear

    placeViewClosed keeps the view to reappear

    Every time I tap on the 'X' button the view shows up again because "presentViewController(gpaViewController, animated: false, completion: nil)" is in "viewDidAppear". So every time "dismissViewControllerAnimated(true, completion: nil)" is called the same view controller loads again.

    How can I make it jump to a new ViewController?

    opened by KarimFikani 1
  • Added explicit downcasting

    Added explicit downcasting

    XCode gave 7 compiler errors due to non-explicit downcasting (e.g. we have to use as! instead of as). Please test before merging as I'm not sure if this will work exactly as intended.

    opened by josh-byster 1
  • Swift 4 upgrade

    Swift 4 upgrade

    It doesn't look like this repo is maintain anymore so in case it helps anyone, I've upgraded to Swift 4, did some refactoring, and even fallback to Apple MapKit if Google Places fails (like for throttling, usage limits, etc): https://github.com/shmidt/GooglePlacesSearchController/pull/15

    opened by basememara 0
  • Syntax error when running on xcode 7.3 swift 2.2

    Syntax error when running on xcode 7.3 swift 2.2

    I am using xcode 7.3 and swift 2.2 it does not compile and give some syntax error

    Currently m using 0.3.0 version of your pod and i tried for 0.2.0 also but that version also throws error to me

    Please let me know which version will be compatible for this swift 2.2 and xcode 7.3

    opened by ImperoIT 0
  • Swift 3.0

    Swift 3.0

    Hello, I updated the code to compile with xcode8 and swift3. I also needed to update the screenshorts for the visual tests, because the rendering on iOS 10 is some pixel different.

    Cheers

    opened by thekie 6
  • Conversion of swift 2.3 code to swift 3

    Conversion of swift 2.3 code to swift 3

    I am having issues related to conversion, whenever I am trying to open xib with button action I am getting this error found nil while unwrapping optional, another issue is related to response http code. If you can provide converted syntax of the code that will be great!

    Thanks

    opened by shrivastavaharsh 15
  • Present the xib from a UITableViewCell

    Present the xib from a UITableViewCell

    Hi. I want to present the view directly when the users taps on a UITableViewCell.(Not presenting an UIViewController that presents the xib. like this the animation seems to be broken.)My UITableView is in a NavigationBar so if I can push the view instead of o modal show so I can have a back buttin instead of the close one. This is what I have in my storyboard: screen shot 2016-08-31 at 15 50 25 And this is the code:

    import UIKit
    
    class GPAViewController: GooglePlacesAutocomplete {
    
    
        override func viewDidLoad() {
            super.viewDidLoad()
            self.placeDelegate = self
            GPAViewController(apiKey: "MY API Key", placeType: .Cities)
    
        }
        override func viewWillAppear(animated: Bool) {
            super.viewWillAppear(animated)
    
        }
    
    
    }
    
    extension GPAViewController: GooglePlacesAutocompleteDelegate {
        func placeSelected(place: Place) {
            print(place)
            let main = stb.instantiateViewControllerWithIdentifier("Menu")
            presentViewController(main, animated: true, completion: nil)
    
    
        }
    
        func placeViewClosed() {
            dismissViewControllerAnimated(false, completion: nil)
        }
    }
    
    opened by perteadrian 0
Owner
Howard Wilson
Howard Wilson
Manage multi-domain url auto mapping ip address table.

Domainer Multi-domain mapper. This library provides manage multi-domain table. Features Manage multi-domain mapping main domain. Find best domain whic

Felix 6 Apr 4, 2020
Get your device ip address, router ip or wifi ssid

FGRoute FGRoute is written on C and Objective C (includes Swift support), it helps developers to get rid of dealing with WiFi interfaces. Example To r

Arthur Sahakyan 137 Dec 5, 2022
Google ProtocolBuffers for Apple Swift

Protocol Buffers for Swift An implementation of Protocol Buffers in Swift. Protocol Buffers are a way of encoding structured data in an efficient yet

Alexey Khokhlov 933 Nov 4, 2022
Approov Integration Examples 0 Jan 26, 2022
Shawn Frank 2 Aug 31, 2022
Approov-service-ios-swift-grpc - Approov service layer for iOS clients using GRPC

Approov Service for GRPC A wrapper for the Approov SDK to enable easy integratio

Approov Integration Examples 0 Jan 21, 2022
Socket framework for Swift using the Swift Package Manager. Works on iOS, macOS, and Linux.

BlueSocket Socket framework for Swift using the Swift Package Manager. Works on iOS, macOS, and Linux. Prerequisites Swift Swift Open Source swift-5.1

Kitura 1.3k Dec 26, 2022
iONess is HTTP Request Helper for iOS platform used by HCI iOS App

iONess iONess (iOS Network Session) is HTTP Request Helper for the iOS platform used by Home Credit Indonesia iOS App. It uses Ergo as a concurrent he

OSFE Homecredit Indonesia 1 Mar 28, 2022
Easy to use OAuth 2 library for iOS, written in Swift.

Heimdallr Heimdallr is an OAuth 2.0 client specifically designed for easy usage. It currently supports the resource owner password credentials grant f

trivago N.V. 628 Oct 17, 2022
OAuth2 framework for macOS and iOS, written in Swift.

OAuth2 OAuth2 frameworks for macOS, iOS and tvOS written in Swift 5.0. ⤵️ Installation ?? Usage ?? Sample macOS app (with data loader examples) ?? Tec

Pascal Pfiffner 1.1k Jan 8, 2023
Swift based OAuth library for iOS

OAuthSwift Swift based OAuth library for iOS and macOS. Support OAuth1.0, OAuth2.0 Twitter, Flickr, Github, Instagram, Foursquare, Fitbit, Withings, L

OAuthSwift 3.1k Jan 6, 2023
Websockets in swift for iOS and OSX

Starscream is a conforming WebSocket (RFC 6455) library in Swift. Features Conforms to all of the base Autobahn test suite. Nonblocking. Everything ha

Dalton 7.5k Jan 4, 2023
SwiftSoup: Pure Swift HTML Parser, with best of DOM, CSS, and jquery (Supports Linux, iOS, Mac, tvOS, watchOS)

SwiftSoup is a pure Swift library, cross-platform (macOS, iOS, tvOS, watchOS and Linux!), for working with real-world HTML. It provides a very conveni

Nabil Chatbi 3.7k Dec 28, 2022
Fast Websockets in Swift for iOS and OSX

SwiftWebSocket Conforming WebSocket (RFC 6455) client library for iOS and Mac OSX. SwiftWebSocket passes all 521 of the Autobahn's fuzzing tests, incl

Josh 1.5k Dec 28, 2022
MQTT for iOS and macOS written with Swift

CocoaMQTT MQTT v3.1.1 client library for iOS/macOS/tvOS written with Swift 5 Build Build with Xcode 11.1 / Swift 5.1 Installation CocoaPods Install us

EMQ X MQTT Broker 1.4k Jan 1, 2023
Minimalistic Swift HTTP request agent for iOS and OS X

Agent Table of Contents Introduction Usage HTTP Verbs Overloading Method Chaining Response Closure Verbs Methods NSMutableURLRequest Contributing Lice

null 589 Jun 29, 2022
Super lightweight async HTTP server library in pure Swift runs in iOS / MacOS / Linux

Embassy Super lightweight async HTTP server in pure Swift. Please read: Embedded web server for iOS UI testing. See also: Our lightweight web framewor

Envoy 540 Dec 15, 2022
A Swift Package that allows iOS apps to communicate with AltServer.

AltKit allows apps to communicate with AltServers on the same WiFi network and enable features such as JIT compilation.

Riley Testut 45 Sep 8, 2022
iOS Network monitor/interceptor framework written in Swift

NetShears NetShears is a Network interceptor framework written in Swift. NetShears adds a Request interceptor mechanisms to be able to modify the HTTP

Divar 119 Dec 21, 2022