我有一个CLLocationCoordinate2D
形式的位置坐标。如何使用Google Maps SDK获得等效的GMSPlace对象?
看来这应该是一个非常简单的任务,但我在Google文档或Stack Overflow中找不到任何内容。
最佳答案
我正在处理类似的问题,但尚未找到确切的解决方案,但是这些替代方法可能会根据您的情况而起作用。如果可以使用GMSAddress
而不是GMSPlace
,则可以将GMSGeocoder与reverseGeocodeCoordinate
一起使用,如下面的选项二所示。
如果您要获取用户的当前位置,则有两个选择:
在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.
}
})
_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
}
有人在here上发布了一个方便的包装程序,可以从
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
}
}
关于ios - 如何获取CLLocationCoordinate2D的GMSPlace?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35140559/