在点击时更改地图叠加的笔触颜色

时间:2017-04-03 04:27:22

标签: ios swift3 mkmapview

我有一个地图视图,我正在生成一堆mkcircle叠加层。它们具有笔触宽度和填充颜色。

我还设置了一个水龙头手势,用于确定水龙头是否在其中一个mkcircles上。我现在要做的是改变笔划宽度和填充颜色,以便用户知道点击了哪个mkcircle,然后在任何其他点击上将其更改回来。

我的代码如下。

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let circleRenderer = MKCircleRenderer(overlay: overlay)
    circleRenderer.fillColor = UIColor.blue.withAlphaComponent(0.1)
    circleRenderer.strokeColor = UIColor.blue
    circleRenderer.lineWidth = 2
    return circleRenderer
}

func handleMapTap(_ gestureReconizer: UITapGestureRecognizer) {
    let tapPoint = gestureReconizer.location(in: mapView)
    let tapCoordinate = mapView.convert(tapPoint, toCoordinateFrom: mapView)
    let point = MKMapPointForCoordinate(tapCoordinate)
    if mapView.overlays.count > 0 {
        for overlay: MKOverlay in polygonArray {
            if (overlay is MKCircle) {
                let circle = overlay
                let circleRenderer = (mapView.renderer(for: circle) as! MKCircleRenderer)
                let datapoint = circleRenderer.point(for: point)
                circleRenderer.invalidatePath()

                if circleRenderer.path.contains(datapoint) {

                    let circleIndex = polygonArray.index{$0 === circle}!
                    print(circleIndex)
                }
            }
        }
    }
}

我已经做了一些搜索,但我还没有找到解决方案。我能够得到tapped circle的circleIndex。

感谢任何指导。

1 个答案:

答案 0 :(得分:1)

万一其他人遇到这个问题的答案实际上很容易实现。

func handleMapTap(_ gestureReconizer: UITapGestureRecognizer) {
    let tapPoint = gestureReconizer.location(in: mapView)
    let tapCoordinate = mapView.convert(tapPoint, toCoordinateFrom: mapView)
    let point = MKMapPointForCoordinate(tapCoordinate)
    if mapView.overlays.count > 0 {
        for overlay: MKOverlay in polygonArray {
            if (overlay is MKCircle) {
                let circle = overlay
                let circleRenderer = (mapView.renderer(for: circle) as! MKCircleRenderer)
                let datapoint = circleRenderer.point(for: point)
                circleRenderer.invalidatePath()

                circleRenderer.fillColor = UIColor.blue.withAlphaComponent(0.1)
                circleRenderer.strokeColor = UIColor.blue

                if circleRenderer.path.contains(datapoint) {

                    circleRenderer.fillColor = UIColor.black
                    circleRenderer.strokeColor = UIColor.black
                    let circleIndex = polygonArray.index{$0 === circle}!
                    print(circleIndex)
                }
            }
        }
    }
}