我正在尝试使用Google Maps从坐标中获取位置详细信息。我以JSON格式获取信息。但是我会遇到以下错误 - "有条件绑定的初始化器必须具有可选类型,而不是'任何''"是我的代码。请指导我如何继续预先感谢
func getAddressForLatLng(currentlocation: CLLocation) {
let baseUrl = "https://maps.googleapis.com/maps/api/geocode/json?"
let apikey = "XYZ"
let url = NSURL(string: "(baseUrl)latlng=(currentlocation.coordinate.latitude),(currentlocation.coordinate.longitude)&key=(apikey)")
let data = NSData(contentsOf: url! as URL)
let json = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
if let result = json["results"] as? NSArray {
let address = result[0]
//should try something here
}
}
我的地址数据是:
{
"address_components" = (
{
"long_name" = "Woodpecker Nature Trail";
"short_name" = "Woodpecker Nature Trail";
types = (
route
);
},
{
"long_name" = "Point Reyes Station";
"short_name" = "Point Reyes Station";
types = (
locality,
political
);
},
{
"long_name" = "Marin County";
"short_name" = "Marin County";
types = (
"administrative_area_level_2",
political
);
},
{
"long_name" = California;
"short_name" = CA;
types = (
"administrative_area_level_1",
political
);
},
{
"long_name" = "United States";
"short_name" = US;
types = (
country,
political
);
},
{
"long_name" = 94956;
"short_name" = 94956;
types = (
"postal_code"
);
}
);
"formatted_address" = "Woodpecker Nature Trail, Point Reyes Station, CA 94956, USA";
geometry = {
bounds = {
northeast = {
lat = "38.0396711";
lng = "-122.8005417";
};
southwest = {
lat = "38.0376697";
lng = "-122.8028458";
};
};
location = {
lat = "38.0376744";
lng = "-122.802158";
};
"location_type" = "GEOMETRIC_CENTER";
viewport = {
northeast = {
lat = "38.0400193802915";
lng = "-122.8003447697085";
};
southwest = {
lat = "38.0373214197085";
lng = "-122.8030427302915";
};
};
};
"place_id" = ChIJAQAAwK7GhYARCiC5K45QogM;
types = (
route
);
}
尝试此代码,
func getAddressForLatLng(latitude: String, longitude: String) {
let url = NSURL(string: "(baseUrl)latlng=(latitude),(longitude)&key=(apikey)")
let data = NSData(contentsOfURL: url!)
let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
if let result = json["results"] as? NSArray {
if let address = result[0]["address_components"] as? NSArray {
let number = address[0]["short_name"] as! String
let street = address[1]["short_name"] as! String
let city = address[2]["short_name"] as! String
let state = address[4]["short_name"] as! String
let zip = address[6]["short_name"] as! String
print("n(number) (street), (city), (state) (zip)")
}
}
}
请参考。
您给出的代码工作正常,所以我认为当您试图将address
对象施加到某物中时,您会遇到错误。
检查下面的代码:
if let result = json["results"] as? NSArray {
if let address = result[0] as? [String: AnyObject] { //Cast your object here
let formatted_address = address["formatted_address"] as? String ?? ""
print(formatted_address) //Here you will get your coordinate address
}
}