Select MKPolygon on tap

时间:2019-04-17 02:44:31

标签: c# xamarin xamarin.forms xamarin.ios

I am trying to allow users to select polygons on a map using xamarin forms iOS and apply a stroke to the ones they have selected. I cannot figure out how to create a tap gesture in c# this way.

I am creating the polygons via

var blockOverlay = MKPolygon.FromCoordinates(coords);
 Constants.nativeMap.AddOverlay(blockOverlay);

Ideally I would like it to look like my Android Map

1 个答案:

答案 0 :(得分:0)

您可以将UITapGestureRecognizer添加到MKMapView并将捕获的抽头坐标转换为地图点,并测试它是否存在于您的叠加层中。

示例:

var uiTapGesture = new UITapGestureRecognizer(tappedGesture =>
{
    foreach (MKPolygon polygon in (tappedGesture.View as MKMapView).Overlays)
    {
        using (var render = new MKPolygonRenderer(polygon))
        {
            var coord2D = nativeMap.ConvertPoint(tappedGesture.LocationInView(nativeMap), nativeMap);
            var mapPoint = MKMapPoint.FromCoordinate(coord2D);
            var polyTouched = render.Path.ContainsPoint(render.PointForMapPoint(mapPoint), true);
            if (polyTouched)
                Console.WriteLine($"tapped: {polygon}");
        }
    }
});
nativeMap.AddGestureRecognizer(uiTapGesture);

注意:这是假设您在叠加层上使用MKPolygon,如果没有,请进行相应调整。