【问题标题】:get zip code with auto complete api使用自动完成 API 获取邮政编码
【发布时间】:2014-05-15 12:07:07
【问题描述】:

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

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

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

【问题讨论】:

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


    【解决方案1】:

    我得到了如下解决方案,

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-27
        • 2016-04-01
        • 2018-05-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多