问题描述
我正在使用 MapKit 的 MKDirection 类在我的应用中获取备用路线,这是显示所有路线的代码。
let directions = MKDirections(request: request)
directions.calculate { response,error in
if error != nil{
self.showAlert(message: "Route not found")
return
}
guard let mapRoute = response?.routes.first else {
return
}
for route in response!.routes{
let newRoute = route
self.mapView.addOverlay(newRoute.polyline)
self.mapView.setVisibleMapRect(
self.mapView.visibleMapRect.union(
newRoute.polyline.boundingMapRect
),edgePadding: UIEdgeInsets(
top: 0,left: padding,bottom: padding,right: padding
),animated: true
)
self.mapRoutes.append(newRoute)
}
}
还为地图添加了点击手势,以便我们可以识别用户选择另一条路线的意图,这里是转换触摸点并将其与地图视图的叠加层进行比较的代码。
但是对于某些点击,我没有得到正确的路线并且选择了错误的叠加层。
@objc func isTappedOnpolygon(with tapGesture:UITapGestureRecognizer) {
let touchPoint = tapGesture.location(in: mapView)
let touchCoordinate = mapView.convert(touchPoint,toCoordinateFrom: mapView)
let mapPoint = MKMapPoint(touchCoordinate)
var selectedOverlay:MKpolyline?
for overlay in mapView.overlays {
if overlay is MKpolyline {
if let polylineRenderer = mapView.renderer(for: overlay) as? MKpolylineRenderer {
let polylinePoint = polylineRenderer.point(for: mapPoint)
if polylineRenderer.path.contains(polylinePoint){
selectedOverlay = overlay as? MKpolyline
break
}
}
}
}
}
谢谢阿伦。
解决方法
你看到这个答案了吗?
尝试为任何缩放级别设置最大 polyLine 宽度:22px。
“此代码检测在每个缩放级别中最大距离为 22 像素的折线上的触摸。只需将您的 UITapGestureRecognizer 指向 handleTap:”