ios 如何从 reverseGeocodeCoordinate 获取国家、州、城市?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15036007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:23:48  来源:igfitidea点击:

How to obtain country, state, city from reverseGeocodeCoordinate?

iosgoogle-maps-sdk-iosreverse-geocoding

提问by user2101384

GMSReverseGeocodeResponsecontains

GMSReverseGeocodeResponse包含

- (GMSReverseGeocodeResult *)firstResult;

whose definition is like:

它的定义是这样的:

@interface GMSReverseGeocodeResult : NSObject<NSCopying>

/** Returns the first line of the address. */
- (NSString *)addressLine1;

/** Returns the second line of the address. */
- (NSString *)addressLine2;

@end

Is there any way to obtain the country, ISO country code, state (administrative_area_1 or corresponding one) from those two strings (valid for all the countriesand all the addresses)?

有没有办法从这两个字符串(对所有国家所有地址有效)中获取国家、ISO 国家代码、州(administrative_area_1 或相应的一个)?

NOTE: I tried to execute this piece of code

注意:我试图执行这段代码

[[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 ) ;
 } ] ;

But for some reason the handler was never called. I did add the app key, and also added the iOS bundle id to the app key. No error is printed in the console. With this I mean I am not aware of the content of the lines.

但由于某种原因,处理程序从未被调用过。我确实添加了应用程序密钥,并将 iOS 包 ID 添加到应用程序密钥。控制台中没有打印错误。我的意思是我不知道这些行的内容。

回答by Pang

The simplest way is to upgrade to Version 1.7of the Google Maps SDK for iOS(released February 2014).
From the release notes:

最简单的办法就是升级到1.7版本的的谷歌地图SDK适用于iOS(发布2014年2月)。
发行说明

GMSGeocodernow provides structured addresses via GMSAddress, deprecating GMSReverseGeocodeResult.

GMSGeocoder现在通过 提供结构化地址GMSAddress,弃用GMSReverseGeocodeResult.

From GMSAddressClass Reference, you can find these properties:

GMSAddressClass Reference 中,您可以找到这些属性

coordinate
Location, or kLocationCoordinate2DInvalidif unknown.

thoroughfare
Street number and name.

locality
Locality or city.

subLocality
Subdivision of locality, district or park.

administrativeArea
Region/State/Administrative area.

postalCode
Postal/Zip code.

country
The country name.

lines
An array of NSStringcontaining formatted lines of the address.

coordinate
位置,或者kLocationCoordinate2DInvalid如果未知。

thoroughfare
街道号码和名称。

locality
地区或城市。

subLocality
地方、地区或公园的细分。

administrativeArea
地区/州/行政区。

postalCode
邮政编码。

country
国名。

lines
NSString包含地址的格式化行的 数组。

No ISO country code though.
Also note that some properties may return nil.

虽然没有 ISO 国家代码。
另请注意,某些属性可能会返回nil

Here's a full example:

这是一个完整的例子:

[[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);
    }
}];

and its output:

及其输出:

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"
)


Alternatively, you may consider using Reverse Geocodingin the The Google Geocoding API(example).

或者,您可以考虑在Google Geocoding API示例)中使用反向地理编码

回答by King-Wizard

Answer in Swift

Swift回答

Using Google Maps iOS SDK (currently using the V1.9.2 you cannot specify the language in which to return results):

使用 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)")
    }
}

Using Google Reverse Geocoding API V3 (currently you can specifythe language in which to return results):

使用 Google Reverse Geocoding API V3(目前您可以指定返回结果的语言):

@IBAction func googleMapsWebServiceGeocodingAPI(sender: UIButton) {
    self.callGoogleReverseGeocodingWebservice(self.currentUserLocation())
}

// #1 - Get the current user's location (latitude, longitude).
private func currentUserLocation() -> CLLocationCoordinate2D {
    // returns current user's 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's country request succeeded !!!\n")

            // The goal here was only for me to get the user's iso country code + 
            // the user's 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's country request: \(error.localizedDescription)\n")
            println("Error GET user's country request: \(operation.responseString)\n")
        }
    )

}

I hope this code snippet and explanation will help future readers.

我希望这段代码片段和解释对未来的读者有所帮助。

回答by Chris Chute

Swift 5 version for addresses in the United States:

适用于美国地址的 Swift 5 版本:

import Foundation
import GoogleMaps

extension GMSAddress {

    var formattedAddress: String {
        let addressComponents = [
            thoroughfare,        // One Infinite Loop
            locality,            // Cupertino
            administrativeArea,  // California
            postalCode           // 95014
        ]
        return addressComponents
            .compactMap { 
  func geocodeCoordinates(location : CLLocation)->String{
         var postalAddress  = ""
        let geocoder = GMSGeocoder()
        geocoder.reverseGeocodeCoordinate(location.coordinate, completionHandler: {response,error in
            if let gmsAddress = response!.firstResult(){
                for line in  gmsAddress.lines! {
                    postalAddress += line + " "
                }
               return postalAddress
            }
        })
        return ""
    }
} .joined(separator: ", ") } }

回答by Mujahid Latif

In swift 4.0 the func gets CLLocation and return postal address

在 swift 4.0 中,func 获取 CLLocation 并返回邮政地址

##代码##