從當前位置獲取附近的地點
先決條件
- 在專案中安裝 pod
- 安裝 GooglePlaces SDK
- 啟用位置服務
首先,我們需要通過獲取當前的經度和緯度來獲取使用者位置。
- 匯入 GooglePlaces 和 GooglePlacePicker
import GooglePlaces
import GooglePlacePicker
- 新增
CLLOcationManagerDelegate
協議
class ViewController: UIViewController, CLLocationManagerDelegate {
}
- 建立你的
CLLocationManager()
var currentLocation = CLLocationManager()
- 請求授權
currentLocation = CLLocationManager()
currentLocation.requetAlwayAuthorization()
- 建立一個按鈕以呼叫 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")
}
})
}
}