Google Places API

suggest change

The Place Picker SDK used here (GooglePlacePicker and GMSPlacePicker) has been shut down. This sample keeps that API. It is Swift 2 (.AuthorizedAlways, pickPlaceWithCallback, NSError). requestAlwaysAuthorization needs NSLocationAlwaysUsageDescription in Info.plist (and the later Always-and-When-In-Use key on newer systems). The location force-unwrap crashes when currentLocation.location is nil. placePicker has to be retained for the callback.

Prerequisites

  1. Install pods in your project.
  2. Install the GooglePlaces SDK.
  3. Enable location services.

First get the user’s location by reading the current longitude and latitude.

  1. Import GooglePlaces, GooglePlacePicker, and CoreLocation.
import GooglePlaces
import GooglePlacePicker
import CoreLocation
  1. Adopt CLLocationManagerDelegate.
class ViewController: UIViewController, CLLocationManagerDelegate {
    var currentLocation = CLLocationManager()
    var placePicker: GMSPlacePicker?
}
  1. Create the CLLocationManager and request authorization.
currentLocation = CLLocationManager()
currentLocation.requestAlwaysAuthorization()
  1. Create a button that calls the place picker. authorizationStatus() is a class method.
@IBAction func placePickerAction(sender: AnyObject) {
    if CLLocationManager.authorizationStatus() == .AuthorizedAlways {
        let center = CLLocationCoordinate2DMake((currentLocation.location?.coordinate.latitude)!, (currentLocation.location?.coordinate.longitude)!)
        let northEast = CLLocationCoordinate2DMake(center.latitude + 0.001, center.longitude + 0.001)
        let southWest = CLLocationCoordinate2DMake(center.latitude - 0.001, center.longitude - 0.001)
        let viewport = GMSCoordinateBounds(coordinate: northEast, coordinate: southWest)
        let config = GMSPlacePickerConfig(viewport: viewport)
        placePicker = GMSPlacePicker(config: config)

        placePicker?.pickPlaceWithCallback({ (place: GMSPlace?, error: NSError?) -> Void in
            if let error = error {
                print("Pick Place error: \(error.localizedDescription)")
                return
            }

            if let place = place {
                print("Place name: \(place.name)")
                print("Address: \(place.formattedAddress)")
            } else {
                print("Place name: nil")
                print("Address: nil")
            }
        })
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents