在地图套件中选择备用路线时出现问题



我正在使用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)
}
}

我们还在地图上添加了点击手势,这样我们就可以识别用户选择另一条路线的意图,下面是转换触摸点并将其与mapview的覆盖进行比较的代码。

但对于一些点击,我没有得到正确的路线和错误的覆盖被选择。

@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像素的多边形线上的触摸。只需将UIMapGestureRecognizer指向handleTap:">

如何检测像Maps.app这样的MKPolylines/Overlay上的点击?

最新更新