MapKit中路径无法显示:如何绘制时序连接的地图路径?
问题:MapKit添加标记后路径不显示的解决方法
你在MapKit地图上添加日程标记并尝试用Path按时间顺序连接,但路径始终不显示——核心问题不是Path不能覆盖MapView,而是你直接把经纬度当作CGPoint绘制,混淆了地理坐标系和视图坐标系。
问题原因
经纬度数值(比如经度116、纬度39)远大于MapView的视图尺寸(通常仅几百pt),直接用经纬度创建CGPoint,Path会被绘制到视图范围之外,自然无法看到。ZStack的层级是正常的,上层Path完全可以覆盖下层MapView。
解决方案
需要把地理坐标(CLLocationCoordinate2D)转换成MapView内部的视图坐标(CGPoint),iOS 17+推荐用MapReader实现坐标转换,代码修改如下:
ZStack { MapReader { proxy in Map(coordinateRegion: $region, annotationItems: markList) { location in MapMarker(coordinate: location.coordinate, tint: .red) } .frame(height: proxyHight * 0.35) .padding([.leading, .trailing], 22) .cornerRadius(20) .shadow(radius: 3, x: 3, y: 3) Path { path in for (index, location) in markList.enumerated() { guard index < markList.count - 1, let startPoint = proxy.convert(location.coordinate, to: .local), let endPoint = proxy.convert(markList[index + 1].coordinate, to: .local) else { continue } path.move(to: startPoint) path.addLine(to: endPoint) } } .stroke(style: StrokeStyle(lineWidth: 2, dash: [5])) .foregroundColor(.blue) } }
代码说明
MapReader提供的proxy对象可完成地理坐标到视图坐标的转换,convert(_:to:)方法中的.local参数指定转换为MapView的本地视图坐标系。- 加入
guard判断是因为如果某个坐标不在当前地图可视区域内,转换会返回nil,此时跳过该段路径绘制即可。
若需兼容iOS 16及以下,需将SwiftUI的Map替换为UIViewRepresentable封装的MKMapView,通过获取地图实例的convert(_:to:)方法完成坐标转换,逻辑和上述一致,仅实现方式略有不同。
内容的提问来源于stack exchange,提问作者Evan Lu
相关产品推荐
相关产品推荐

