如何在swiftUI中获得当前坐标跨度?



我正在使用地图套件地图,我需要获得坐标跨度模型的当前值。所以当你点击地图点时,地图本身不会跳跃。

import SwiftUI
import MapKit
struct MapScreenView: View {
@StateObject private var vm = LocationsViewModel()
var body: some View {
ZStack {
VStack {
HStack {
ButtonFilterView()
Spacer()
}
Spacer()
}.zIndex(1)
Map(coordinateRegion:
$vm.mapRegion, annotationItems: vm.locations) {
location in
MapAnnotation(coordinate: location.coordinate) {
LocationMapAnnotationView()
.scaleEffect(vm.mapLocation == location ? 1.1 : 0.7)
.animation(.easeInOut, value: vm.mapLocation == location)
.onTapGesture {
vm.showTappedLocation(location: location)
}
}
}
.edgesIgnoringSafeArea(.all)
}
}
}
struct MapScreenView_Previews: PreviewProvider {
static var previews: some View {
MapScreenView()
}
}


import Foundation
import MapKit
import SwiftUI
class LocationsViewModel: ObservableObject {
@Published var locations: [Location] = LocationDataService.locations

@Published var mapLocation: Location {
didSet {
updateMapRegion(location: mapLocation)
}
}
@Published var mapRegion = MKCoordinateRegion()
@Published var mapSpan = MKCoordinateSpan(latitudeDelta: 0.04, longitudeDelta: 0.04)

init() {
self.mapLocation = Location(name: "", coordinate: CLLocationCoordinate2D(latitude: 55.755864, longitude: 37.617698))
updateMapRegion(location: Location(name: "", coordinate: CLLocationCoordinate2D(latitude: 55.755864, longitude: 37.617698)))
}
private func updateMapRegion(location: Location) {
withAnimation(.easeInOut) {
mapRegion = MKCoordinateRegion(
center: location.coordinate,
/// here i want get current span value
span: location.name == "" ? MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1) : mapSpan
)
}
}
func showTappedLocation(location: Location) {
mapLocation = location
}
}

当我单击地图引脚时,它返回到硬代码范围。如何得到当前张成的空间?我寻找了许多解决方案,但没有找到正确的

SwiftUIMap绑定到MKCoordinateRegion

在你的代码中你有…

Map(coordinateRegion: $vm.mapRegion, ...

这是视图模型的区域和地图视图之间的双向通信。当地图更新时,这个区域也会更新。当你更新区域时,地图也随之更新。

所以你的地图的当前值是帮助里面的mapRegion

查看MKCoordinateRegion文档https://developer.apple.com/documentation/mapkit/mkcoordinateregion/1452293-span

它有一个属性span,它是一个MKCoordinateSpan

在视图模型中。这是当前地图的span

要更新你的函数,你可以这样做…

private func updateMapRegion(location: Location) {
withAnimation(.easeInOut) {
mapRegion = MKCoordinateRegion(
center: location.coordinate,
/// here i want get current span value
span: mapRegion.span
)
}
}

话虽如此,你似乎在这里创造了一个全新的区域。我不知道这是不是个好主意。你可以只更新现有区域的中心,而不需要创建一个全新的区域。

private func updateMapRegion(location: Location) {
withAnimation(.easeInOut) {
mapRegion.center = location.coordinate
}
}

相关内容

  • 没有找到相关文章

最新更新