如何解决使用SwiftUI Mapkit调整地图大小的问题
我想在应用程序上放大我的地图,我尝试使用 latitudinalMeters: 300
、longitudinalMeters: 300
或使用 latitudeDelta: 0.001
旋转。他们两个都没有工作。
我也选择了 (0,0)
作为我的中心,但是每次我在模拟器上运行时,我都以 (37.326010,-122.026056)
作为我的中心。显然,我在位置管理器中设置的中心和区域的默认设置都不适用于 ContentView。
这是我的 LocationManager.swift 代码:
import Foundation
import CoreLocation
import MapKit
class LocationManager: NSObject,ObservableObject{
let locationManager = CLLocationManager()
@Published var location: CLLocation?
@Published var region: MKCoordinateRegion
override init(){
self.region = MKCoordinateRegion(center: CLLocationCoordinate2D.init(latitude: 0,longitude: 0),latitudinalMeters: 300,longitudinalMeters: 300)
super.init()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
}
extension LocationManager : CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager,didUpdateLocations locations: [CLLocation]){
guard let location = locations.last else { return }
self.region = MKCoordinateRegion(center: location.coordinate,longitudinalMeters: 300)
self.location = location
}
}
这是我的ContentView:
struct ContentView: View {
var body: some View {
MapView2()
}
}
struct MapView2: View {
@Observedobject var locationManager = LocationManager()
var body: some View {
let coord = locationManager.location?.coordinate
let lat = coord?.latitude ?? 0
let lon = coord?.longitude ?? 0
return vstack {
Map(coordinateRegion: $locationManager.region,interactionModes: .all,showsUserLocation: true,userTrackingMode: .constant(.follow))
}
}
}
解决方法
至于使用 MapKit 的 SwiftUI,我不会使用 CoreLocation 框架。您可以使用 .onChange
修饰符对视图执行缩放更改。如果需要,您可以使用带有 SwiftUI 手势的 @State var zoom
来执行它们,或者任何可以实时进行这些更改的东西。我在滑块中添加了两个按钮来放大或缩小示例。
import SwiftUI
import MapKit
struct ContentView: View {
var body: some View {
MapsView()
}
}
struct MapsView: View {
@State var zoom: CGFloat = 15
@State var mapCoordinate = MKCoordinateRegion(
center: CLLocationCoordinate2D(
latitude: 38.989202809314854,longitude: -76.93626224283602),span: MKCoordinateSpan(
latitudeDelta: .zero,longitudeDelta: .zero))
var body: some View {
VStack(spacing: 16) {
Map(coordinateRegion: $mapCoordinate)
.ignoresSafeArea(edges: .all)
// You can see the changes being operating by the .onChange modifier.
Slider(value: $zoom,in: 0.01...50,minimumValueLabel: Image(systemName: "plus.circle"),maximumValueLabel: Image(systemName: "minus.circle"),label: {})
.padding(.horizontal)
.onChange(of: zoom) { value in
mapCoordinate.span.latitudeDelta = CLLocationDegrees(value)
mapCoordinate.span.longitudeDelta = CLLocationDegrees(value)
}
}
.font(.title)
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。