Find city name and country from latitude and longitude in Swift

前端 未结 11 1941
既然无缘
既然无缘 2020-12-12 22:58

I\'m working on application in Swift3 and I have letter problem i can\'t find the answer for it.

How can I know city name and country short names base on latitud

相关标签:
11条回答
  • 2020-12-12 23:15

    I would recommend integrating Google Maps API with your project. If you do, your task can be achieved using Reverse Geocoding Google provides.

    Furthermore, Google there is Google Maps SDK for IOS development, which is also worth considering.

    UPD: You can do that without integrating maps into your project. Basing on this answer, you can achieve that using http requests to Google API. The request to:

    https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=API_KEY 
    

    would return JSON object with information about the requested place, including country and city name.

    BTW, I highly recommend using Alamofire to make http requests in Swift.

    0 讨论(0)
  • 2020-12-12 23:16

    This method will give you the current location, city name ,country name etc.

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location: CLLocation = locations.last!
        print("Location: \(location)")
    
        let geocoder = CLGeocoder()
        geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
            // Process Response
            if let error = error {
                print("Unable to Reverse Geocode Location (\(error))")
            } else {
                if let placemarks = placemarks, let placemark = placemarks.first {
                    self.city = placemark.locality!
    
                    //self.country = placemark.country!
                }
            }
        }
    
        let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude,
                                              longitude: location.coordinate.longitude,
                                              zoom: zoomLevel)
    
         self.locationv = CLLocation(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
    
        if myView.isHidden {
            myView.isHidden = false
            myView.camera = camera
        } else {
            myView.animate(to: camera)
        }
    }
    
    0 讨论(0)
  • 2020-12-12 23:17

    1 . import CoreLocation 2 . insert CLLocationManagerDelegate in your class 3 . Do the delegate methods described below... hope it will help you you can find city name and country through following these steps...Here is my code

        import UIKit
    
        import CoreLocation 
    
        class MyViewController:UIViewController,CLLocationManagerDelegate {
        override func viewDidLoad() {
            super.viewDidLoad()
    
    
            self.locationManager.delegate = self
            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
            self.locationManager.requestWhenInUseAuthorization()
            self.locationManager.requestAlwaysAuthorization()
            self.locationManager.startUpdatingLocation()
    
    
    }
    
        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
    
    
            if( CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
                CLLocationManager.authorizationStatus() ==  .authorizedAlways){
    
               if let currentLocation = locationManager.location
               {
    
               if NetworkFunctions.NetworkRechability()
               {
    
                getAddressFromLatLon(pdblLatitude: "\(Double((currentLocation.coordinate.latitude)))", withLongitude: "\(Double((currentLocation.coordinate.longitude)))")
    
                }
    
                }
            }
    
    
    
        }
    
        func getAddressFromLatLon(pdblLatitude: String, withLongitude pdblLongitude: String) {
            var center : CLLocationCoordinate2D = CLLocationCoordinate2D()
            let lat: Double = Double("\(pdblLatitude)")!
    
            let lon: Double = Double("\(pdblLongitude)")!
    
            let ceo: CLGeocoder = CLGeocoder()
            center.latitude = lat
            center.longitude = lon
    
            let loc: CLLocation = CLLocation(latitude:center.latitude, longitude: center.longitude)
    
    
            ceo.reverseGeocodeLocation(loc, completionHandler:
                {(placemarks, error) in
                    if (error != nil)
                    {
                    }
    
                    if placemarks != nil
                    {
    
                        let pm = placemarks! as [CLPlacemark]
    
                        if pm.count > 0 {
    
                            let pm = placemarks![0]
    
                            print(pm.country ?? "")
                            print(pm.locality ?? "")
                           print(pm.subLocality ?? "")
                           print(pm.thoroughfare ?? "")
                            print(pm.postalCode ?? "")
                            print(pm.subThoroughfare ?? "")
                            var addressString : String = ""
                            if pm.subLocality != nil {
                                addressString = addressString + pm.subLocality! + ", "
                            }
                            if pm.thoroughfare != nil {
                                addressString = addressString + pm.thoroughfare! + ", "
                            }
                            if pm.locality != nil {
                                addressString = addressString + pm.locality! + ", "
                                if pm.country != nil {
                                    addressString = addressString + pm.country! + ", "
                                    //uuuuu
                                    if(location_city != pm.locality!.trimmingCharacters(in: .whitespaces))
                                    {
                                        location_city=pm.locality!.trimmingCharacters(in: .whitespaces)
                                          DispatchQueue.main.async{
                                        self.GetBeeWatherDetails(district: pm.locality!, country: pm.country!)
                                        }
                                    }
                                }
    
                            }
    
                            if pm.postalCode != nil {
                                addressString = addressString + pm.postalCode! + " "
                            }
    
                        }
                    }
            })
    
        }
    
    }
    
    0 讨论(0)
  • 2020-12-12 23:17

    Add this extension in your swift file.

    extension CLLocation {
    func fetchAddress(completion: @escaping (_ address: String?, _ error: Error?) -> ()) {
        CLGeocoder().reverseGeocodeLocation(self) {
            let palcemark = $0?.first
            var address = ""
            if let subThoroughfare = palcemark?.subThoroughfare {
                address = address + subThoroughfare + ","
            }
            if let thoroughfare = palcemark?.thoroughfare {
                address = address + thoroughfare + ","
            }
            if let locality = palcemark?.locality {
                address = address + locality + ","
            }
            if let subLocality = palcemark?.subLocality {
                address = address + subLocality + ","
            }
            if let administrativeArea = palcemark?.administrativeArea {
                address = address + administrativeArea + ","
            }
            if let postalCode = palcemark?.postalCode {
                address = address + postalCode + ","
            }
            if let country = palcemark?.country {
                address = address + country + ","
            }
            if address.last == "," {
                address = String(address.dropLast())
            }
            completion(address,$1)
           // completion("\($0?.first?.subThoroughfare ?? ""), \($0?.first?.thoroughfare ?? ""), \($0?.first?.locality ?? ""), \($0?.first?.subLocality ?? ""), \($0?.first?.administrativeArea ?? ""), \($0?.first?.postalCode ?? ""), \($0?.first?.country ?? "")",$1)
        }
    }
    

    }

    And then call it on any of the CLLocation object.

    Eg:

     (myLocation as? CLLocation)!.fetchAddress { (address, error) in
                            guard let address = address, error == nil else                              
    {return }
    
    0 讨论(0)
  • 2020-12-12 23:21

    You can use CLGeocoder, from CoreLocation, for that. From Apple documentation (emphasizes mine):

    A single-shot object for converting between geographic coordinates and place names.

    The CLGeocoder class provides services for converting between a coordinate (specified as a latitude and longitude) and the user-friendly representation of that coordinate. A user-friendly representation of the coordinate typically consists of the street, city, state, and country information corresponding to the given location...

    This service is unrelated to MapKit and, as such, don't require you use/show a map in your app at all.

    0 讨论(0)
  • 2020-12-12 23:21

    See my answer in swift 4.1 Xcode 9.4.1. You can get even village name details also. Get location name from Latitude & Longitude in iOS

    0 讨论(0)
提交回复
热议问题