运行代码后找到了要在地图上标注的代码,但无法与我的主代码结合。我的主要代码使用 map( .... ) 在 mapkit 上插入地图,但注释代码使用“MapView”,如下所示,
SwiftUI 上 int Map 的 MapView 版本
MapView(centerCoordinate: $centerCoordinate, annotations: locations)
.edgesIgnoringSafeArea(.all)
SwiftUI 上 int Map 的地图版本
Map(coordinateRegion: $viewModel.region,
interactionModes: .all,
showsUserLocation: true,
annotationItems: annotationItems)
我得到的代码能够以双精度(纬度和经度)获取用户值并在地图上进行注释。
我更习惯使用 map(...) 设置,但我得到的注释来自 mapView,这是另一个设置。
我很难将它们组合在一起。
我可以在运行代码之前在地图上注释,但我想要的是在 int 地图之后更新,我似乎找不到代码来注释地图(...)格式。
mapview(...) 版本是,
Button(action: {
let savedLat = Double(textFieldLat) // Lat value
let savedLong = Double(textFieldLong) // Long value
let newLocation = MKPointAnnotation()
newLocation.coordinate = CLLocationCoordinate2D(latitude: savedLat ?? 0, longitude: savedLong ?? 0)
self.locations.append(newLocation)
})
更新地图
struct MapView: UIViewRepresentable{
...
...
...
func updateUIView(_ view: MKMapView, context: Context) {
if annotations.count != view.annotations.count {
view.addAnnotations(annotations)
}
}
}
感谢您的宝贵时间!
Map
是一个原生的 SwiftUI 视图,它根据 SwiftUI 的 Map doc 嵌入了一个地图界面,而 MKMapView
是一个可嵌入地图界面(doc)的类。我不认为你可以将它们结合起来 -
Apple 开发者论坛中的这篇文章 建议如果MKMapView
无法满足您的需求,或提交功能请求,请使用Map
。
Map
更易用,可以动态更新Map 旨在更易于使用。我也在寻找如何将注释标记添加到
Map
XCode 的 MapKit 和 SwiftUI 教程,官方文档缺乏有用的示例。
这是一个代码示例,说明我如何根据传入的坐标初始化然后动态更新标记。如果您需要呈现多个标记,您可以改为将其他项目添加到
markers
列表,然后像Apple论坛中的这个例子一样迭代它们中的每一个。
import SwiftUI
import MapKit
struct Marker: Identifiable {
let id = UUID()
var location: MapMarker
}
struct MapView: View {
var coordinate: CLLocationCoordinate2D
@State private var region = MKCoordinateRegion()
@State var markers = [Marker(location: MapMarker(coordinate: CLLocationCoordinate2D(latitude: -96.8311, longitude: 145.0602), tint: .blue))]
var body: some View {
Map(coordinateRegion: $region, annotationItems: markers) { marker in
marker.location }
.onAppear {
setRegion(coordinate)
}
}
private func setRegion(_ coordinate: CLLocationCoordinate2D) {
region = MKCoordinateRegion(
center: coordinate,
span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
)
markers = [Marker(location: MapMarker(coordinate: coordinate, tint: .blue))]
}
}
struct MapView_Previews: PreviewProvider {
static var previews: some View {
MapView(coordinate: CLLocationCoordinate2D(latitude: -36.8311, longitude: 145.0602))
}
}