如何解决允许用户在显示其位置的同时在地图上移动
我希望允许用户在应用程序跟踪和显示其当前位置时放大/缩小并在地图上自由移动。稍后我将尝试添加一个您可以按下的按钮,它会将您移回用户位置的中心。我认为问题是在我的 LocationManager 文件中,我每次获得新的位置坐标时都会创建新区域。但我不知道其他任何跟踪和显示用户位置的方法。
位置管理器:
import Foundation
import CoreLocation
import MapKit
class LocationManager: NSObject,ObservableObject,CLLocationManagerDelegate{
let locationManager = CLLocationManager()
@Published var location: CLLocationCoordinate2D?
@Published var region = MKCoordinateRegion()
override init(){
super.init()
locationManager.delegate = self
}
func startTracking() {
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLdistanceFilterNone
locationManager.allowsBackgroundLocationUpdates = true
locationManager.startUpdatingLocation()
}
func stopTracking() {
print("stop test")
locationManager.stopUpdatingLocation()
locationManager.allowsBackgroundLocationUpdates = false
}
func locationManager(_ manager: CLLocationManager,didUpdateLocations locations: [CLLocation]) {
let tempLocation = locations.last?.coordinate
print(tempLocation)
let center = CLLocationCoordinate2D(latitude: tempLocation?.latitude ?? 0.0,longitude: tempLocation?.longitude ?? 0.0)
let span = MKCoordinateSpan(latitudeDelta: 0.5,longitudeDelta: 0.5)
let tempRegion = MKCoordinateRegion(center: center,span: span)
dispatchQueue.main.async {
self.location = tempLocation
self.region = tempRegion
}
}
}
内容视图:
import SwiftUI
import MapKit
struct ContentView: View {
@State var isButtonpressed: Bool = false
@StateObject var locationManager = LocationManager()
var body: some View {
vstack{
Button("START"){
isButtonpressed = true
locationManager.startTracking()
}
Button("STOP"){
isButtonpressed = false
locationManager.stopTracking()
}
mapView(isButtonpressed: isButtonpressed,manager: locationManager)
}
}
}
struct mapView: View{
var isButtonpressed: Bool
@Observedobject var manager: LocationManager
@State var defaultRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 0,longitude: 0),latitudinalMeters: 1000,longitudinalMeters: 1000)
var body: some View{
if isButtonpressed == true{
if let location = manager.location {
Map(coordinateRegion: $manager.region,interactionModes: .all,showsUserLocation: true,userTrackingMode:nil)
} else{
Map(coordinateRegion: $defaultRegion)
}
}
else
{
Map(coordinateRegion: $defaultRegion)
}
}
}
谢谢!
解决方法
创建一系列区域是监控用户位置的错误方式。
我已经有一段时间没有编写地图应用程序了,但以下是您应该做什么的总体思路:
创建位置管理器的实例。
将自己设置为位置经理的代表。
在您的应用运行时向用户请求获取位置更新的权限(如果您还没有权限。)
调用 startUpdatingLocation()
请求位置更新
根据需要响应对位置管理器委托的 locationManager(_:didUpdateLocations:)
方法的调用。 (如果您将地图设置为显示用户的位置,则无需执行任何特殊操作 - 蓝点会自动更新。)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。