Android查找多边形的交集?

时间:2012-07-30 08:29:42

标签: java android android-mapview

我目前有一些多边形形状,如下图所示,使用以下代码绘制到我的mapview上

enter image description here

    CustomPolygon customPolygon= data.getCustomPolygonList().get(i);
            Path path = new Path();
            path.setFillType(Path.FillType.EVEN_ODD);
            for(int n=0;n<customPolygon.getCorrdinateList().size();n++)
            {

                GeoPoint sector1 = new GeoPoint((int)(customPolygon.getCorrdinateList().get(n).getLatitude()*1e6), (int)((customPolygon.getCorrdinateList().get(n).getLongitude())*1e6));
                if(n==0){
                    mapView.getProjection().toPixels(sector1, point1_draw);
                    path.moveTo(point1_draw.x,point1_draw.y);
                }else
                {
                    mapView.getProjection().toPixels(sector1, point1_draw);
                    path.lineTo(point1_draw.x,point1_draw.y);
                }
            }

            path.close();
            canvas.drawPath(path, paint);

现在我正在弄清楚如何知道ontap按钮是否与任何多边形相交。例如,如果它与多边形之一相交,则消息将显示当前多边形。

我被困在覆盖的ontap部分。

    @Override
public boolean onTap(GeoPoint p, MapView ) {



        Point point1_draw = new Point();     
        mapView.getProjection().toPixels(p, point1_draw);


        for (int i =0;i<data.getCustomPolygonList().size();i++)
        {
            CustomPolygon customPolygon= data.getCustomPolygonList().get(i);
            for(int n=0;n<customPolygon.getCorrdinateList().size();n++)
            {
            }

        }

    return  true;
}

2 个答案:

答案 0 :(得分:1)

我假设您需要一些代码来检查按钮是否在多边形内?

我现在不能给你代码,但这是一个粗略的算法:

for each line segment in the polygon
  calculate the dot product for the line segment and the line formed by the starting vertex and the point to check
  if all dot products have the same sign, the point is inside the polygon

请注意,要使其工作,您需要多边形具有连续的绕组,即所有顶点都是顺时针或逆时针添加的。此外,这种方法可能并不总是适用于凹多边形。因此,您可能希望将凹多边形分割为一系列凸多边形。

对于更一般(但也更昂贵)的算法,请查看此Wiki页面:http://en.wikipedia.org/wiki/Point_in_polygon

另一个信息来源(以及一些代码):How can I determine whether a 2D Point is within a Polygon?

答案 1 :(得分:0)

我很惊讶android.graphics.Path和android.graphics.PathMeasure没有为此提供API。它应该。

algotithm是described here