首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获得经度和纬度,然后将其存储在变量上?斯威夫特论

如何获得经度和纬度,然后将其存储在变量上?斯威夫特论
EN

Stack Overflow用户
提问于 2022-07-05 08:08:20
回答 1查看 67关注 0票数 -1

因此,我尝试制作一个程序来检索用户的位置,这一次我想获取该区域中的纬度和经度,但是如何检索它们并将它们存储在一个变量中

代码语言:javascript
复制
import SwiftUI
import MapKit
import CoreLocationUI

struct ContentView: View {
  @StateObject private var viewModel = ContentViewModel()
    @State var LongStorage : Int = 0
    @State var LangStorage : Int = 0
    var body: some View {
        ZStack(alignment: .bottom){
            Map(coordinateRegion: $viewModel.region, showsUserLocation: true)
                .ignoresSafeArea()
                .tint(Color("GreenColor"))
            
            
            LocationButton(.currentLocation){
                viewModel.requestAllowOnceLocationPermission()
            }
            .foregroundColor(.white )
            .cornerRadius(10)
            .labelStyle(.titleAndIcon)
            .symbolVariant(.fill)
            .tint(Color("GreenColor"))
            .padding(.bottom, 50)
            
            
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

final class ContentViewModel: NSObject, ObservableObject, CLLocationManagerDelegate{
    
    @Published var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude:  40, longitude: 120), span: MKCoordinateSpan(latitudeDelta: 100, longitudeDelta: 100))
    
    let locationManager = CLLocationManager()
    
    override init() {
        super.init()
        locationManager.delegate = self
    }
    
    func requestAllowOnceLocationPermission()  {
        locationManager.requestLocation()
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let latestLocation = locations.first else{
            //Show an error
            return
        }
        DispatchQueue.main.async {
            self.region = MKCoordinateRegion(center: latestLocation.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.015, longitudeDelta: 0.015))
//check region value
            print("Region --> \(self.region)")
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error.localizedDescription)
    }
}

这就是终点站的结果,我怎么才能得到经纬度?

代码语言:javascript
复制
Region --> MKCoordinateRegion(center: __C.CLLocationCoordinate2D(latitude: 37.33036067, longitude: -122.02845007), span: __C.MKCoordinateSpan(latitudeDelta: 0.015, longitudeDelta: 0.015))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-05 08:38:29

您已经获得了最新位置的值,所以只需将它们赋值给变量:

代码语言:javascript
复制
var latitude = region.center.latitude
var logitude = region.center.longitude

对我来说很难测试,因为不能只是复制粘贴您的代码来尝试它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72866019

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档