Как получить страну, штат, город от reverseGeocodeCoordinate?
GMSReverseGeocodeResponse
содержит
- (GMSReverseGeocodeResult *)firstResult;
определение которого выглядит так:
@interface GMSReverseGeocodeResult : NSObject<NSCopying>
/** Returns the first line of the address. */
- (NSString *)addressLine1;
/** Returns the second line of the address. */
- (NSString *)addressLine2;
@end
Есть ли способ получить страну, код страны ISO, state (Administrative_area_1 или соответствующий) из этих двух строк (действительный для всех стран и всех адресов)?
ПРИМЕЧАНИЕ. Я попытался выполнить этот фрагмент кода
[[GMSGeocoder geocoder] reverseGeocodeCoordinate:CLLocationCoordinate2DMake(40.4375, -3.6818) completionHandler:^(GMSReverseGeocodeResponse *resp, NSError *error)
{
NSLog( @"Error is %@", error) ;
NSLog( @"%@" , resp.firstResult.addressLine1 ) ;
NSLog( @"%@" , resp.firstResult.addressLine2 ) ;
} ] ;
Но почему-то обработчик никогда не вызывался. Я добавил ключ приложения, а также добавил идентификатор пакета iOS к ключу приложения. В консоли не отображается ошибка. Я имею в виду, что я не знаю содержание строк.
Ответы
Ответ 1
Самый простой способ - обновить до версии 1.7 Google Maps SDK для iOS (выпущен в феврале 2014 г.).
Из примечания к выпуску:
GMSGeocoder
теперь предоставляет структурированные адреса с помощью GMSAddress
, осуждая GMSReverseGeocodeResult
.
Из GMSAddress
Ссылка на класс, вы можете найти эти свойства:
coordinate
Расположение или kLocationCoordinate2DInvalid
, если неизвестно.
thoroughfare
Номер улицы и имя.
locality
Местность или город.
subLocality
Подразделение местности, района или парка.
administrativeArea
Регион/Штат/Административный район.
postalCode
Почтовый/Почтовый индекс.
country
Название страны.
lines
Массив NSString
, содержащий отформатированные строки адреса.
Нет кода страны ISO, хотя.
Также обратите внимание, что некоторые свойства могут возвращать nil
.
Вот полный пример:
[[GMSGeocoder geocoder] reverseGeocodeCoordinate:CLLocationCoordinate2DMake(40.4375, -3.6818) completionHandler:^(GMSReverseGeocodeResponse* response, NSError* error) {
NSLog(@"reverse geocoding results:");
for(GMSAddress* addressObj in [response results])
{
NSLog(@"coordinate.latitude=%f", addressObj.coordinate.latitude);
NSLog(@"coordinate.longitude=%f", addressObj.coordinate.longitude);
NSLog(@"thoroughfare=%@", addressObj.thoroughfare);
NSLog(@"locality=%@", addressObj.locality);
NSLog(@"subLocality=%@", addressObj.subLocality);
NSLog(@"administrativeArea=%@", addressObj.administrativeArea);
NSLog(@"postalCode=%@", addressObj.postalCode);
NSLog(@"country=%@", addressObj.country);
NSLog(@"lines=%@", addressObj.lines);
}
}];
и его вывод:
coordinate.latitude=40.437500
coordinate.longitude=-3.681800
thoroughfare=(null)
locality=(null)
subLocality=(null)
administrativeArea=Community of Madrid
postalCode=(null)
country=Spain
lines=(
"",
"Community of Madrid, Spain"
)
В качестве альтернативы вы можете использовать Reverse Geocoding в Геокодирование Google API (example).
Ответ 2
Ответ в Swift
Используя Google Maps iOS SDK (в настоящее время с использованием V1.9.2 вы не можете указать язык, на котором нужно возвращать результаты):
@IBAction func googleMapsiOSSDKReverseGeocoding(sender: UIButton) {
let aGMSGeocoder: GMSGeocoder = GMSGeocoder()
aGMSGeocoder.reverseGeocodeCoordinate(CLLocationCoordinate2DMake(self.latitude, self.longitude)) {
(let gmsReverseGeocodeResponse: GMSReverseGeocodeResponse!, let error: NSError!) -> Void in
let gmsAddress: GMSAddress = gmsReverseGeocodeResponse.firstResult()
print("\ncoordinate.latitude=\(gmsAddress.coordinate.latitude)")
print("coordinate.longitude=\(gmsAddress.coordinate.longitude)")
print("thoroughfare=\(gmsAddress.thoroughfare)")
print("locality=\(gmsAddress.locality)")
print("subLocality=\(gmsAddress.subLocality)")
print("administrativeArea=\(gmsAddress.administrativeArea)")
print("postalCode=\(gmsAddress.postalCode)")
print("country=\(gmsAddress.country)")
print("lines=\(gmsAddress.lines)")
}
}
Используя Google Reverse Geocoding API V3 (в настоящее время вы можете указать язык, на котором будут возвращаться результаты):
@IBAction func googleMapsWebServiceGeocodingAPI(sender: UIButton) {
self.callGoogleReverseGeocodingWebservice(self.currentUserLocation())
}
// #1 - Get the current user location (latitude, longitude).
private func currentUserLocation() -> CLLocationCoordinate2D {
// returns current user location.
}
// #2 - Call Google Reverse Geocoding Web Service using AFNetworking.
private func callGoogleReverseGeocodingWebservice(let userLocation: CLLocationCoordinate2D) {
let url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=\(userLocation.latitude),\(userLocation.longitude)&key=\(self.googleMapsiOSAPIKey)&language=\(self.googleReverseGeocodingWebserviceOutputLanguageCode)&result_type=country"
AFHTTPRequestOperationManager().GET(
url,
parameters: nil,
success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
println("GET user country request succeeded !!!\n")
// The goal here was only for me to get the user iso country code +
// the user Country in english language.
if let responseObject: AnyObject = responseObject {
println("responseObject:\n\n\(responseObject)\n\n")
let rootDictionary = responseObject as! NSDictionary
if let results = rootDictionary["results"] as? NSArray {
if let firstResult = results[0] as? NSDictionary {
if let addressComponents = firstResult["address_components"] as? NSArray {
if let firstAddressComponent = addressComponents[0] as? NSDictionary {
if let longName = firstAddressComponent["long_name"] as? String {
println("long_name: \(longName)")
}
if let shortName = firstAddressComponent["short_name"] as? String {
println("short_name: \(shortName)")
}
}
}
}
}
}
},
failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
println("Error GET user country request: \(error.localizedDescription)\n")
println("Error GET user country request: \(operation.responseString)\n")
}
)
}
Я надеюсь, что этот фрагмент кода и объяснение помогут будущим читателям.