iosjsonswiftgoogle-maps

How to request postal code using geocoding from Google Maps SDK in swift?


I am trying to make an app that uses postal code. The problem is there is not proper documentation for postal code related data parsing for Google SDKs in swift...I want to get the postal code of the user on the basis of the generated latitude and longitude.


Solution

  • func getAddressFromLatLong(latitude: Double, longitude : Double) {
      let url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=\ 
      (latitude),\(longitude)&key=YOUR_API_KEY_HERE"
    
    Alamofire.request(url).validate().responseJSON { response in
        switch response.result {
        case .success:
    
            let responseJson = response.result.value! as! NSDictionary
    
            if let results = responseJson.object(forKey: "results")! as? [NSDictionary] {
                if results.count > 0 {
                    if let addressComponents = results[0]["address_components"]! as? [NSDictionary] {
                        self.address = results[0]["formatted_address"] as? String
                        for component in addressComponents {
                            if let temp = component.object(forKey: "types") as? [String] {
                                if (temp[0] == "postal_code") {
                                    self.pincode = component["long_name"] as? String
                                }
                                if (temp[0] == "locality") {
                                    self.city = component["long_name"] as? String
                                }
                                if (temp[0] == "administrative_area_level_1") {
                                    self.state = component["long_name"] as? String
                                }
                                if (temp[0] == "country") {
                                    self.country = component["long_name"] as? String
                                }
                            }
                        }
                    }
                }
            }
            case .failure(let error):
              print(error)
          }
       }
    }