获取自动完成api的邮政编码

时间:2014-05-15 12:07:08

标签: ios iphone ipad google-maps google-maps-api-3

如何在iOS中使用谷歌的自动完整api获取邮政编码?

我已经尝试了google place api但它没有返回邮政编码

所以,请任何人有解决方案给我一些想法

2 个答案:

答案 0 :(得分:2)

我得到了如下解决方案,

 CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        [geocoder geocodeAddressString:item.completionText completionHandler:^(NSArray* placemarks, NSError* error){
            for (CLPlacemark* aPlacemark in placemarks)
            {
                tfAddress.placeholder = @"Loading...";

                // Process the placemark.
                NSString *strLatitude = [NSString stringWithFormat:@"%.4f",aPlacemark.location.coordinate.latitude];
                NSString *strLongitude = [NSString stringWithFormat:@"%.4f",aPlacemark.location.coordinate.longitude];

                NSString *yourURL =[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=%@,%@&sensor=true_or_false",strLatitude,strLongitude];

                AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

                manager.requestSerializer = [AFJSONRequestSerializer serializer];

                [manager POST:yourURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

                    NSArray *data = [[[responseObject objectForKey:@"results"] objectAtIndex:0]valueForKey:@"address_components"];
                    NSString *strZip;
                    for (NSDictionary *dict in data)
                    {
                        if ([[[dict valueForKey:@"types"] objectAtIndex:0] length]>10)
                        {
                            if ([[[[dict valueForKey:@"types"] objectAtIndex:0] substringToIndex:11] isEqualToString:@"postal_code"])
                            {
                                strZip = [dict valueForKey:@"long_name"];
                            }
                        }
                    }

                    NSLog(@"JSON: %@", responseObject);

                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

                    tfAddress.placeholder = @"Zip Code";

                    NSLog(@"Error: %@", error);
                }];
            }
        }];
        NSLog(@"Autocompleted with: %@", item.completionText);

答案 1 :(得分:1)

使用谷歌地图iOS SDK Swift:

@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反向地理编码Objective-C:

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

}

有关详细信息,请查看here