路径无法在地图上显示

问题描述 投票:0回答:1

我尝试将时间表的位置添加为MapKit地图上的地图标记,并按时间顺序连接它们。 enter image description here 但路径没有出现,我确信

start
end
位于正确的位置。所以我想知道 Path 是否不允许覆盖 MapView?如果是这样。我如何实现这个?

ZStack{
                    Map(coordinateRegion: $region, annotationItems: markList) { location in
                        MapMarker(coordinate: CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude), tint: .red)
                    }
                    .frame(height: proxyHight * 0.35)
                    .padding([.leading, .trailing], 22)
                    .cornerRadius(20)
                    .shadow( radius: 3, x: 3, y: 3)
                    
                    Path { path in
                            // Draw dotted lines between markers
                            for (index, location) in markList.enumerated() {
                                if index < markList.count - 1 {
                                    let nextLocation = markList[index + 1].coordinate
                                    let start = CGPoint(x: location.coordinate.longitude, y: location.coordinate.latitude)
                                    let end = CGPoint(x: nextLocation.longitude, y: nextLocation.latitude)
                                    //print("Drawing line from \(start) to \(end)")
                                    path.move(to: start)
                                    path.addLine(to: end)
                                }
                            }
                        }
                        .stroke(style: StrokeStyle(lineWidth: 2, dash: [5]))
                        .foregroundColor(Color.blue)
                    
                  
                    }

swift swiftui mapkit
1个回答
0
投票

您传递给

CGPoint
Path
代表 视图空间 中的点,而不是地球上的坐标。 (0, 0) 将是屏幕左上角的点,而不是非洲附近海洋中的某个位置。

在 iOS 17 之前,SwiftUI 的

Map
功能非常有限,在地图上准确绘制线条是非常困难。我建议用
MKMapView
包裹
UIViewRepresentable
这个要点展示了一个简单的例子。

在 iOS 17+ 中,您应该使用

MapPolyline
,它可以在地图上绘制路径。

假设

markList.map(\.coordinate)
是一个
[CLLocationCoordinate2D]
,你可以写:

Map(initialPosition: .region(region)) {
    ForEach(markList) { mark in
        Marker("", coordinate: mark.coordinate)
    }
    MapPolyline(coordinates: markList.map(\.coordinate))
        .stroke(.blue, style: StrokeStyle(lineWidth: 2, dash: [5]))
}

注意,如果需要追踪地图区域,应该使用

onMapCameraChange
:

.onMapCameraChange(frequency: .continuous) {
    // do something with $0.region
}
© www.soinside.com 2019 - 2024. All rights reserved.