小编典典

在Swift中从经纬度中查找城市名称和国家/地区

swift

我正在Swift3中开发应用程序,但遇到字母问题,我找不到答案。

我怎么知道基于纬度和经度的城市名称和国家简称?

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate{
    let locationManager = CLLocationManager()
    var latitude: Double = 0
    var longitude: Double = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        // For use when the app is open & in the background
        locationManager.requestAlwaysAuthorization()
        // For use when the app is open
        //locationManager.requestWhenInUseAuthorization()
        locationManager.delegate = self
        locationManager.startUpdatingLocation()
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.startUpdatingLocation()
        }
    }
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.first {
            print(location.coordinate)
            latitude = location.coordinate.latitude
            longitude = location.coordinate.longitude
        }
    }
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if (status == CLAuthorizationStatus.denied){
            showLocationDisabledpopUp()
        }
    }
    func showLocationDisabledpopUp() {
        let alertController = UIAlertController(title: "Background Location Access  Disabled", message: "We need your location", preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        alertController.addAction(cancelAction)
        let openAction = UIAlertAction(title: "Open Setting", style: .default) { (action) in
            if let url = URL(string: UIApplicationOpenSettingsURLString){
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }
        alertController.addAction(openAction)
        self.present(alertController, animated: true, completion: nil)
    }
}

阅读 492

收藏
2020-07-07

共1个答案

小编典典

我建议将Google Maps
API
与您的项目集成。如果您这样做,则可以使用Google提供的反向地理编码来完成您的任务。

此外,谷歌还有用于IOS开发的Google Maps
SDK
,这也是值得考虑的。

UPD:
您可以在不将地图集成到项目中的情况下做到这一点。基于答案,您可以使用对Google
API的http请求来实现这一目标。要求:

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

将返回JSON带有有关所请求地点信息的对象,包括国家和城市名称。

顺便说一句,我强烈建议使用Alamofire在Swift中发出http请求。

2020-07-07