Search code examples
swiftgoogle-mapsgoogle-geocoderclgeocoder

convert LAT/Long to Location address in iOS swift


I am trying to convert my current Lat and long to current address details. so, i am using this url to get the response from google

https://maps.googleapis.com/maps/api/geocode/json?latlng=12.9892037613554,80.2505832381126&key="MyAPI Key"

But only first two times only its giving response, once i saved the api changes in the google developer console credentials. After that it gives the status of "REQUEST DENIED"

{
"error_message": "This IP, site or mobile application is not authorized to use this API key. Request received from IP address "My ip address", with empty referer",
"html_attributions": [],
"results": [],
"status": "REQUEST_DENIED"
} 

And i also try with the CLGeocoder.

let geocoder = CLGeocoder()
    geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
        if (error != nil){
            print("error in reverseGeocode")
        }
        let placemark = placemarks! as [CLPlacemark]
        if placemark.count>0{
            let placemark = placemarks![0]
            print(placemark.locality!)
            print(placemark.administrativeArea!)
            print(placemark.country!)

            print("\(placemark.locality!), \(placemark.administrativeArea!), \(placemark.country!)")
        }
    }

by the use of geocoder some of places not showing correctly. so please suggest me to get the address of my current location in iOS Swift


Solution

  • Use Following code for Swift 3.0 only need to pass lat long by calling this function.Hope this will help you.

       func latLong(lat: Double,long: Double)  {
    
        let geoCoder = CLGeocoder()
        let location = CLLocation(latitude: lat , longitude: long)
        geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
    
            print("Response GeoLocation : \(placemarks)")
            var placeMark: CLPlacemark!
            placeMark = placemarks?[0]
    
            // Country
            if let country = placeMark.addressDictionary!["Country"] as? String {
                print("Country :- \(country)")
                // City
                if let city = placeMark.addressDictionary!["City"] as? String {
                    print("City :- \(city)")
                    // State
                    if let state = placeMark.addressDictionary!["State"] as? String{
                        print("State :- \(state)")
                        // Street
                        if let street = placeMark.addressDictionary!["Street"] as? String{
                            print("Street :- \(street)")
                            let str = street
                            let streetNumber = str.components(
                                separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")
                            print("streetNumber :- \(streetNumber)" as Any)
    
                            // ZIP
                            if let zip = placeMark.addressDictionary!["ZIP"] as? String{
                                print("ZIP :- \(zip)")
                                // Location name
                                if let locationName = placeMark?.addressDictionary?["Name"] as? String {
                                    print("Location Name :- \(locationName)")
                                    // Street address
                                    if let thoroughfare = placeMark?.addressDictionary!["Thoroughfare"] as? NSString {
                                    print("Thoroughfare :- \(thoroughfare)")
    
                                    }
                                }
                            }
                        }
                    }
                }
            }
        })
    }
    

    Or

     let geocoder = CLGeocoder()
                    geocoder.geocodeAddressString(addressSingle!, completionHandler: {(placemarks, error) -> Void in
                        if((error) != nil){
                            print("Error", error ?? "")
                        }
                        if let placemark = placemarks?.first {
                            let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate
                            print("Lat: \(coordinates.latitude) -- Long: \(coordinates.longitude)")
    
                            let position = CLLocationCoordinate2DMake(coordinates.latitude,coordinates.longitude)
                            let marker = GMSMarker(position: position)
    
                            marker.snippet = addressSingle
                            marker.map = self.viewMap
                            let camera = GMSCameraPosition.camera(withLatitude: coordinates.latitude, longitude: coordinates.longitude, zoom: 18)
                            self.viewMap?.animate(to: camera)
    
                            // Change color of marker
                            marker.icon = GMSMarker.markerImage(with: .red)
                        }
                    })
    

    where addressSingle is a String address from API