Google Maps get address from latitude and Longitude iOS Swift
If you are implemented the google maps in your application then you can use your core location framework to get the current latitude and Longitude.Then pass the lat and Long to the below function and get the address to the passed lat, long.It will be got from google Places API.
Code:
func getAddressForLatLng(latitude: String, longitude: String) -> String {
func getAddressForLatLng(latitude: String, longitude: String) -> String {
let url = NSURL(string: "https://maps.googleapis.com/maps/api/geocode/json?latlng=\(latitude),\(longitude)&key=\(googlePlacesapiKey)")
let data = NSData(contentsOf: url! as URL)
if data != nil {
let json = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
if let result = json["results"] as? NSArray {
if result.count > 0 {
if let addresss:NSDictionary = result[0] as! NSDictionary {
if let address = addresss["address_components"] as? NSArray {
var newaddress = ""
var number = ""
var street = ""
var city = ""
var state = ""
var zip = ""
if(address.count > 1) {
number = (address.object(at: 0) as! NSDictionary)["short_name"] as! String
}
if(address.count > 2) {
street = (address.object(at: 1) as! NSDictionary)["short_name"] as! String
}
if(address.count > 3) {
city = (address.object(at: 2) as! NSDictionary)["short_name"] as! String
}
if(address.count > 4) {
state = (address.object(at: 4) as! NSDictionary)["short_name"] as! String
}
if(address.count > 6) {
zip = (address.object(at: 6) as! NSDictionary)["short_name"] as! String
}
newaddress = "\(number) \(street), \(city), \(state) \(zip)"
return newaddress
}
else {
return ""
}
}
} else {
return ""
}
}
else {
return ""
}
} else {
return ""
}
}
This comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDelete