【问题标题】:How to request postal code using geocoding from google maps sdk in swift?如何在 swift 中使用 google maps sdk 的地理编码请求邮政编码?
【发布时间】:2020-03-15 23:24:11
【问题描述】:

我正在尝试制作一个使用邮政编码的应用程序。问题是没有适当的文档在swift中为google sdks解析邮政编码相关数据...我想根据生成的纬度和经度获取用户的邮政编码

【问题讨论】:

    标签: ios json swift api google-maps


    【解决方案1】:
    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)
          }
       }
    }
    

    【讨论】:

    • 是的,你可以试试
    猜你喜欢
    • 2017-10-04
    • 2011-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 2018-01-03
    • 2011-11-28
    相关资源
    最近更新 更多