Google Places API
suggest changeThe 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
- Install pods in your project.
- Install the GooglePlaces SDK.
- Enable location services.
First get the user’s location by reading the current longitude and latitude.
- Import GooglePlaces, GooglePlacePicker, and CoreLocation.
import GooglePlaces
import GooglePlacePicker
import CoreLocation
- Adopt
CLLocationManagerDelegate.
class ViewController: UIViewController, CLLocationManagerDelegate {
var currentLocation = CLLocationManager()
var placePicker: GMSPlacePicker?
}
- Create the
CLLocationManagerand request authorization.
currentLocation = CLLocationManager()
currentLocation.requestAlwaysAuthorization()
- 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")
}
})
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents