RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1257495
Accepted
Sherstyuk
Sherstyuk
Asked:2022-03-18 16:23:41 +0000 UTC2022-03-18 16:23:41 +0000 UTC 2022-03-18 16:23:41 +0000 UTC

SwiftUI:如何获取 MapView 中心坐标并将它们输出到文本?

  • 772

地图中心有一个红色十字准线,我需要获取这个十字准线所在的坐标,并在 Text 中显示出来。

在此处输入图像描述

有猜测是这样的

func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
            
            let currentLocation = mapView.centerCoordinate
                    print("👉 Координаты \(currentLocation)")

}

项目链接

swiftui
  • 2 2 个回答
  • 10 Views

2 个回答

  • Voted
  1. Best Answer
    VAndrJ
    2022-03-19T15:37:39Z2022-03-19T15:37:39Z

    您只需要将坐标“扔”到可以绘制它们的位置。根据该项目,这MapViewModel

    我不会深入研究其中发生的事情,例如它已添加@Published,并且已经适应您的需求:

    class MapViewModel: NSObject, ObservableObject, CLLocationManagerDelegate {
        @Published var center: CLLocationCoordinate2D?
    ...
    // В координаторе добавлен @Binding
    class Coordinator: NSObject, MKMapViewDelegate {
        @Binding var center: CLLocationCoordinate2D?
    
        init(center: Binding<CLLocationCoordinate2D?>) {
            self._center = center
        }
    ...
    // Естественно его нужно передать:
    func makeCoordinator() -> Coordinator {
        return MapView.Coordinator(center: $mapData.center)
    }
    ...
    // И использовать:
    if let center = mapData.center {
        Text("Мои координаты: В: \(center.latitude) L: \(center.longitude)")
    }
    

    结果:

    在此处输入图像描述

    • 1
  2. Sherstyuk
    2022-03-20T17:30:56Z2022-03-20T17:30:56Z

    我将发布项目的完整代码,也许有人会派上用场

    主页.swift

    import SwiftUI
    import CoreLocation
    import MapKit
    
    struct Home: View {
        
        @StateObject var mapData = MapViewModel()
        // Location Manager....
        @State var locationManager = CLLocationManager()
    
        
        // Целик
        struct Cross: Shape {
            func path(in rect: CGRect) -> Path {
                return Path { path in
                    path.move(to: CGPoint(x: rect.midX, y: 0))
                    path.addLine(to: CGPoint(x: rect.midX, y: rect.maxY))
                    path.move(to: CGPoint(x: 0, y: rect.midY))
                    path.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))
                    path.move(to: CGPoint(x: rect.midX, y: rect.midY))
                    path.addArc(center: CGPoint(x: rect.midX, y: rect.midY), radius: 10, startAngle: Angle(degrees: 0), endAngle: Angle(degrees: 360), clockwise: false)
                }
            }
        }
        
        var body: some View {
            
            ZStack {
                // Карта
                MapView()
                    .environmentObject(mapData)
                    .ignoresSafeArea(.all, edges: .all)
                
                // Целик
                Cross().stroke(Color.red)
                               .frame(width: 90, height: 90)
                
                // Всё что по верх карты
                VStack {
                    VStack(spacing: 0) {
                        // Панель поиска
                        HStack {
                            Image(systemName: "magnifyingglass")
                                .foregroundColor(.gray)
                            TextField("Search", text: $mapData.searchTxt)
                                .colorScheme(.light)
                        }
                        .padding(.vertical,10)
                        .padding(.horizontal)
                        .background(Color.white)
                        // Displaying Results...
                        if !mapData.places.isEmpty && mapData.searchTxt != "" {
                            ScrollView {
                                VStack(spacing: 15) {
                                    ForEach(mapData.places) {place in
                                        Text(place.placemark.name ?? "")
                                            .foregroundColor(.black)
                                            .frame(maxWidth: .infinity,alignment: .leading)
                                            .padding(.leading)
                                            .onTapGesture{
                                                mapData.selectPlace(place: place)
                                            }
                                        Divider()
                                    }
                                }
                                .padding(.top)
                            }
                            .background(Color.white)
                        }
                        
                    } .padding()
                    Spacer()
                    // Панель кнопок
                    VStack {
                        Button(action: mapData.focusLocation, label: {
                            Image(systemName: "location.fill")
                                .font(.title2)
                                .padding(10)
                                .background(Color.primary)
                                .clipShape(Circle())
                        })
                        Button(action: mapData.updateMapType, label: {
                            Image(systemName: mapData.mapType == .standard ? "network" : "map")
                                .font(.title2)
                                .padding(10)
                                .background(Color.primary)
                                .clipShape(Circle())
                        })
                        if let center = mapData.center {
                            Text ("Мои координаты: В: \(center.latitude) L: \(center.longitude)")
                        }
                    }
                    .frame(maxWidth: .infinity, alignment: .trailing)
                    .padding()
                    
                }
                
            }
            .onAppear(perform: {
                // Setting Delegate...
                locationManager.delegate = mapData
                locationManager.requestWhenInUseAuthorization()
            })
            // Permission Denied Alert...
            .alert(isPresented: $mapData.permissionDenied, content: {
                Alert(title: Text("Permission Denied"), message: Text("Please Enable Permission In App Settings"), dismissButton: .default(Text("Go Setting"), action: {
                    // Redireting User To Settings...
                    UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
                }))
            })
            .onChange(of: mapData.searchTxt, perform: { value in
                // Searching Places...
                // You can use your own delay time to avoid Continous Search Request...
                let delay = 0.3
                DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
                    if value == mapData.searchTxt {
                        // Search...
                        self.mapData.searchQuery()
                    }
                    
                }
                
            })
        }
        
        func regionToString(_ region: MKCoordinateRegion) -> String {
            "\(region.center.latitude), \(region.center.longitude)"
        }
    }
    
    struct Home_Previews: PreviewProvider {
        static var previews: some View {
            Home()
            
        }
    }
    
    

    MapView.swift

    import SwiftUI
    import MapKit
    
    struct MapView: UIViewRepresentable {
        @EnvironmentObject var mapData: MapViewModel
        
        
        func makeCoordinator() -> Coordinator {
            return MapView.Coordinator(center: $mapData.center)
        }
        
        func makeUIView(context: Context) -> MKMapView {
            let view = mapData.mapView
            view.showsCompass = false
            view.showsUserLocation = true
            view.delegate = context.coordinator
            
            let compassBtn = MKCompassButton(mapView: view)
                    compassBtn.frame.origin = CGPoint(x: 20, y: 100) // you may use GeometryReader to replace it's position
            compassBtn.compassVisibility = .adaptive // compass will always be on map
            view.addSubview(compassBtn)
    
            return view
            
        }
        
        func updateUIView(_ uiView: MKMapView, context: Context) {
            //
            print("Updating")
        
        }
        
        class Coordinator: NSObject,MKMapViewDelegate {
            @Binding var center: CLLocationCoordinate2D?
            
            init(center: Binding<CLLocationCoordinate2D?>) {
                self._center = center
            }
            
            func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
                // Custom Pins....
                // Excluding User Blue Circle...
                if annotation.isKind(of: MKUserLocation.self){return nil}
                else{
                    let pinAnnotation = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "PIN_VIEW")
                    pinAnnotation.tintColor = .red
                    pinAnnotation.animatesDrop = true
                    pinAnnotation.canShowCallout = true
                    return pinAnnotation
                }
                
            }
            
            
            func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
                
                let currentLocation = mapView.centerCoordinate
                        print("👉 Координаты \(currentLocation)")
                center = currentLocation
            
            }
        
        }
    }
    
    

    MapViewModel.swift

    import SwiftUI
    import MapKit
    import CoreLocation
    // All Map Data Goes Here....
    class MapViewModel: NSObject,ObservableObject,CLLocationManagerDelegate{
        @Published var center: CLLocationCoordinate2D?
        @Published var mapView = MKMapView()
    // Region...
        @Published var region : MKCoordinateRegion!
        // Based On Location It Will Set Up....
    // Alert...
        @Published var permissionDenied = false
        // Map Type...
        @Published var mapType : MKMapType = .standard
        // SearchText...
        @Published var searchTxt = ""
        // Searched Places...
        @Published var places : [Place] = []
        // Updating Map Type...
        func updateMapType(){
            if mapType == .standard{
                mapType = .hybrid
                mapView.mapType = mapType
            } else {
                mapType = .standard
                mapView.mapType = mapType
            }
        }
        // Focus Location...
        func focusLocation() {
            guard let _ = region else{return}
            mapView.setRegion(region, animated: true)
            mapView.setVisibleMapRect(mapView.visibleMapRect, animated: true)
        }
        // Search Places...
        func searchQuery(){
            places.removeAll()
            let request = MKLocalSearch.Request()
            request.naturalLanguageQuery = searchTxt
    // Fetch...
            MKLocalSearch(request: request).start { (response, _) in
                guard let result = response else{return}
                self.places = result.mapItems.compactMap({ (item) -> Place? in
                    return Place(placemark: item.placemark)
                })
            }
        }
        // Pick Search Result...
        func selectPlace(place: Place) {
            // Showing Pin On Map....
            searchTxt = ""
            guard let coordinate = place.placemark.location?.coordinate else{return}
            let pointAnnotation = MKPointAnnotation()
            pointAnnotation.coordinate = coordinate
            pointAnnotation.title = place.placemark.name ?? "No Name"
            // Removing All Old Ones...
            mapView.removeAnnotations(mapView.annotations)
            mapView.addAnnotation(pointAnnotation)
            // Moving Map To That Location...
            let coordinateRegion = MKCoordinateRegion(center: coordinate, latitudinalMeters: 10000, longitudinalMeters: 1000 )
            mapView.setRegion(coordinateRegion, animated: true)
            mapView.setVisibleMapRect(mapView.visibleMapRect, animated: true)
        }
        
        func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
            // Checking Permissions...
            switch manager.authorizationStatus {
            case .denied:
    // Alert...
                permissionDenied.toggle()
            case .notDetermined:
                // Requesting....
                manager.requestWhenInUseAuthorization()
            case .authorizedWhenInUse:
                // If Permissin Given...
                manager.requestLocation()
            default:()
            }
        }
        
        func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    // Error....
            print(error.localizedDescription)
        }
        // Getting user Region....
        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            guard let location = locations.last else{return}
            self.region = MKCoordinateRegion(center: location.coordinate, latitudinalMeters: 10000, longitudinalMeters: 1000)
            // Updating Map....
            self.mapView.setRegion(self.region, animated: true)
            // Smooth Animations...
            self.mapView.setVisibleMapRect(self.mapView.visibleMapRect, animated: true)
            
            print(location.coordinate)
        }
    
    }
    
    
    • 0

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    表格填充不起作用

    • 2 个回答
  • Marko Smith

    提示 50/50,有两个,其中一个是正确的

    • 1 个回答
  • Marko Smith

    在 PyQt5 中停止进程

    • 1 个回答
  • Marko Smith

    我的脚本不工作

    • 1 个回答
  • Marko Smith

    在文本文件中写入和读取列表

    • 2 个回答
  • Marko Smith

    如何像屏幕截图中那样并排排列这些块?

    • 1 个回答
  • Marko Smith

    确定文本文件中每一行的字符数

    • 2 个回答
  • Marko Smith

    将接口对象传递给 JAVA 构造函数

    • 1 个回答
  • Marko Smith

    正确更新数据库中的数据

    • 1 个回答
  • Marko Smith

    Python解析不是css

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5