【问题标题】:How to obtain country, state, city from reverseGeocodeCoordinate?如何从reverseGeocodeCoordinate获取国家、州、城市?
【发布时间】:2013-02-08 18:27:24
【问题描述】:

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 国家代码、州(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 捆绑包 ID 添加到应用程序密钥。控制台中不会打印任何错误。我的意思是我不知道这些行的内容。

【问题讨论】:

标签: ios google-maps-sdk-ios reverse-geocoding


【解决方案1】:

最简单的方法是升级到版本 1.7 Google Maps SDK for iOS(2014 年 2 月发布)。
来自release notes

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

GMSAddress Class Reference,你可以找到these properties

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

或者,您可以考虑在The Google Geocoding API (example) 中使用Reverse Geocoding

【讨论】:

    【解决方案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(目前可以specify返回结果的语言):

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

    希望这段代码sn-p和解释对以后的读者有所帮助。

    【讨论】:

      【解决方案3】:

      用于美国地址的 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 { $0 }
                  .joined(separator: ", ")
          }
      
      }
      

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 2019-05-27
          • 2013-11-13
          • 1970-01-01
          • 2017-10-20
          • 2011-01-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多