【问题标题】:Swift Update Latitude and LongitudeSwift 更新经纬度
【发布时间】:2017-06-16 02:42:15
【问题描述】:

我想在每次按下按钮时提取和更新纬度和经度并显示用户在初始位置的位置,更新位置非常重要,因为它是附近的应用程序,这是我的代码:

var locationManager = CLLocationManager()


@IBAction func update(_ sender: Any) {
    locationManager.startUpdatingLocation()


}
override func viewDidAppear(_ animated: Bool) {

    super.viewDidAppear(animated)

    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()



    let url = URL(string: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=\(latitude),\(longitude)radius=5000&types=gas_station&key=AIzaSyDVyaidSrF37d0M6XrHvosTXK4z-rkoLDg")!

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let userLocation: CLLocation = locations[0]

    let latitude = userLocation.coordinate.latitude

    let longitude = userLocation.coordinate.longitude

    let latDelta: CLLocationDegrees = 0.05

    let lonDelta: CLLocationDegrees = 0.05

    let span: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)

    let location: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)

    let region: MKCoordinateRegion = MKCoordinateRegion(center: location, span: span)


    map.setRegion(region, animated: true)


    locationManager.stopUpdatingLocation()
}

【问题讨论】:

    标签: swift dictionary location


    【解决方案1】:

    您有一个 CLLocationManager。您可以随时获取设备的位置

    locationManager.location
    

    这是一个CLLocation。我要警告的一件事是 requestAuthorization 等......需要几秒钟,并且该位置将为零,直到它完成并且 CLLocationManager 已开始定位。因此,在解包选项时要小心,并考虑在之前的 VC 中创建您的 locationManager 并请求授权。一个完整的 IBAction,获取用户的位置,并在 URL 中插入 lat 和 long:

    @IBAction func pushed(_ sender: Any) {
        if let location = locationManager.location {
              let url = URL(string: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=\(location.coordinate.latitude),\(location.coordinate.longitude)radius=5000&types=gas_station&key=AIzaSyDVyaidSrF37d0M6XrHvosTXK4z-rkoLDg")!
              // Now do whatever you need to do with the URL, at this point
        }
    }
    

    【讨论】:

    • 我可能错了,但看起来 OP 已经在 did update location 方法中获得了一个位置。 IMO,他只想在按下按钮时使用该信息创建一个 URL
    • 我是如何实现的
    • 我的印象是,每次按下按钮时,他都想获取纬度和经度。 @JuanJoseRodrigo:你能澄清一下你在找什么吗?
    • 我想用用户拥有的新经纬度更新网址
    • 我想我明白了。所以你想要:按下按钮 -> 获取当前位置(经纬度) -> 在 googleapi URL 中输入位置?我会更新我的帖子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2023-03-29
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多