如何获得国家,州,市的reverseGeocodeCoordinate?(How to obtain

2019-07-20 09:35发布

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的应用程序的关键。 印在控制台中没有错误。 有了这个,我的意思是我不知道该行的内容。

Answer 1:

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

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

另外,您也可以考虑使用反向地理编码中的谷歌地理编码API ( 例如 )。



Answer 2:

斯威夫特

使用谷歌地图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)")
    }
}

使用谷歌反向地理编码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")
        }
    )

}

我希望这个代码片断和解释将有助于未来的读者。



Answer 3:

在SWIFT 4.0 FUNC得到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 ""
    }


文章来源: How to obtain country, state, city from reverseGeocodeCoordinate?