从当前位置获取附近的地点

先决条件

  1. 在项目中安装 pod
  2. 安装 GooglePlaces SDK
  3. 启用位置服务

首先,我们需要通过获取当前的经度和纬度来获取用户位置。

  1. 导入 GooglePlaces 和 GooglePlacePicker
import GooglePlaces
import GooglePlacePicker
  1. 添加 CLLOcationManagerDelegate 协议
class ViewController: UIViewController, CLLocationManagerDelegate {
    
}
  1. 创建你的 CLLocationManager()
var currentLocation = CLLocationManager()
  1. 请求授权
currentLocation = CLLocationManager()
currentLocation.requetAlwayAuthorization()
  1. 创建一个按钮以调用 GooglePlacePicker 方法

@IBAction func placePickerAction(sender:AnyObject){

if CLLOcationManager.authorizationStatues() == .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")
            }
        })
    }        
}