![](/img/trans.png)
[英]MKPolygon - How to determine if a CLLocationCoordinate2D is in a CLLocationCoordinate2D polygon?
[英]How to get GMSPlace for a CLLocationCoordinate2D?
我有一個CLLocationCoordinate2D
形式的位置坐標。 如何使用Google Maps SDK獲取其等效的GMSPlace對象?
這似乎應該是一個非常簡單的任務,但我在Google的文檔或Stack Overflow中找不到任何內容。
我正在研究類似的問題,我沒有找到確切的解決方案,但這些替代方案可能會根據您的情況而有效。 如果您可以使用GMSAddress
而不是GMSPlace
,則可以使用GMSGeocoder調用reverseGeocodeCoordinate
如下面的選項二所示。
如果您嘗試獲取用戶的當前位置,有兩個選項:
使用Google地圖當前位置獲取GMSPlace。 這很簡單,如果你只是訴諸實際的地方就可以解決你的問題。 這個問題是我無法弄清楚如何獲得所有地址(而不是企業)。 您可以在此處查看文檔。
在viewDidLoad中:
let placesClient = GMSPlacesClient()
當你想要獲得當前的位置時:
placesClient?.currentPlaceWithCallback({ (placeLikelihoods, error) -> Void in if error != nil { // Handle error in some way. } if let placeLikelihood = placeLikelihoods?.likelihoods.first { let place = placeLikelihood.place // Do what you want with the returned GMSPlace. } })
使用OneShotLocationManager獲取CLLocationCoordinate2D並將其轉換為GMSAddress。 您必須使用以下代碼替換_didComplete
函數以返回GMSAddress而不是CLLocationCoordinate2D。
private func _didComplete(location: CLLocation?, error: NSError?) { locationManager?.stopUpdatingLocation() if let location = location { GMSGeocoder().reverseGeocodeCoordinate(location.coordinate, completionHandler: { [unowned self] (response, error) -> Void in if error != nil || response == nil || response!.firstResult() == nil { self.didComplete?(location: nil, error: NSError(domain: self.classForCoder.description(), code: LocationManagerErrors.InvalidLocation.rawValue, userInfo: nil)) } else { self.didComplete?(location: response!.firstResult(), error: error) } }) } else { self.didComplete?(location: nil, error: error) } locationManager?.delegate = nil locationManager = nil }
有人在這里貼了一個方便的包裝器來從GMSAddressComponents
中提取你在處理這個API時可能會覺得有用的字段。 這很容易,因為當你想要訪問城市時,你所要做的就是以place.addressComponents?.city
為例。
extension CollectionType where Generator.Element == GMSAddressComponent {
var streetAddress: String? {
return "\(valueForKey("street_number")) \(valueForKey(kGMSPlaceTypeRoute))"
}
var city: String? {
return valueForKey(kGMSPlaceTypeLocality)
}
var state: String? {
return valueForKey(kGMSPlaceTypeAdministrativeAreaLevel1)
}
var zipCode: String? {
return valueForKey(kGMSPlaceTypePostalCode)
}
var country: String? {
return valueForKey(kGMSPlaceTypeCountry)
}
func valueForKey(key: String) -> String? {
return filter { $0.type == key }.first?.name
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.