【问题标题】:Polygon Touch detection Google Map API V2多边形触摸检测 Google Map API V2
【发布时间】:2013-01-18 18:48:42
【问题描述】:

我正在尝试找出最好的方法,我有一张地图,上面画了一个Polygon。因为 Google Maps API V2 似乎没有在多边形上进行触摸检测。我想知道是否可以检测到触摸点是否在多边形内部?如果是这样,那么如何,我的主要目标是在地图上勾勒出一个状态,当用户点击该状态时,它将在自定义视图中显示更多详细信息。到目前为止,我能够捕获地图的MapOnClick,但是当用户在Polygon 内点击时,我想要在Toast 上设置polygon.getID()。我是新手,如果我不够清楚,我很抱歉。

googleMap.setOnMapClickListener(new OnMapClickListener() 
    {
        public void onMapClick(LatLng point) 
        {
        boolean checkPoly = true;

        Toast.makeText(MainActivity.this,"The Location is outside of the Area", Toast.LENGTH_LONG).show();
        }    
     });
     }
     }
   catch (Exception e) {
         Log.e("APP","Failed", e);
     }    

好的,这就是我目前为止的半工作

    private boolean rayCastIntersect(LatLng tap, LatLng vertA, LatLng vertB) {

    double aY = vertA.latitude;
    double bY = vertB.latitude;
    double aX = vertA.longitude;
    double bX = vertB.longitude;
    double pY = tap.latitude;
    double pX = tap.longitude;
     if (aY > bY) {
            aX = vertB.longitude;
            aY = vertB.latitude;
            bX = vertA.longitude;
            bX = vertA.latitude;
        }
    System.out.println("aY: "+aY+" aX : "+aX);
    System.out.println("bY: "+bY+" bX : "+bX);

     if (pX < 0) pX += 360;
        if (aX < 0) aX += 360;
        if (bX < 0) bX += 360;

        if (pY == aY || pY == bY) pY += 0.00000001;
        if ((pY > bY || pY < aY) || (pX > Math.max(aX, bX))) return false;
        if (pX < Math.min(aX, bX))

            return true;
//  }

    double m = (aX != bX) ? ((bY - aY) / (bX - aX)) : aX;
    double bee = (aX != pX) ? ((pY - aY) / (pX - aX)) : aX;
    double x = (pY - bee) / m;

    return x > pX;
}

}

我遇到的问题是触摸在每个多边形的左侧都是真实的,直到它到达另一个多边形。我的算法有什么问题会导致这个问题?任何帮助将不胜感激。

【问题讨论】:

  • 所以澄清一下,您是否想弄清楚您的触摸是否发生在多边形的地理范围内?

标签: java android coordinates google-maps-android-api-2 point-in-polygon


【解决方案1】:

您要解决的问题是Point in Polygon 测试。

帮助可视化光线投射的概念:

在一张纸上画一个多边形。然后,从任意随机点开始,在页面右侧画一条直线。如果您的线与多边形相交奇数次,这意味着您的起点在多边形内。


那么,如何在代码中做到这一点?

您的多边形由顶点列表组成:ArrayList&lt;Geopoint&gt; vertices。您需要单独查看每个Line Segment,并查看您的Ray 是否与它相交

private boolean isPointInPolygon(Geopoint tap, ArrayList<Geopoint> vertices) {
    int intersectCount = 0;
    for(int j=0; j<vertices.size()-1; j++) {
        if( rayCastIntersect(tap, vertices.get(j), vertices.get(j+1)) ) {
            intersectCount++;
        }
    }

    return (intersectCount%2) == 1); // odd = inside, even = outside;
}

private boolean rayCastIntersect(Geopoint tap, Geopoint vertA, Geopoint vertB) {

    double aY = vertA.getLatitude();
    double bY = vertB.getLatitude();
    double aX = vertA.getLongitude();
    double bX = vertB.getLongitude();
    double pY = tap.getLatitude();
    double pX = tap.getLongitude();

    if ( (aY>pY && bY>pY) || (aY<pY && bY<pY) || (aX<pX && bX<pX) ) {
        return false; // a and b can't both be above or below pt.y, and a or b must be east of pt.x
    }

    double m = (aY-bY) / (aX-bX);               // Rise over run
    double bee = (-aX) * m + aY;                // y = mx + b
    double x = (pY - bee) / m;                  // algebra is neat!

    return x > pX;
}

【讨论】:

  • 好的,马特,我让它工作了我唯一的问题是,如果两个多边形在同一个 x 路径上,它会将它们视为一个并为它们使用相同的 id 号。有什么想法吗?
  • 嗯,你能详细说明一下吗?我想象你的意思是,如果两个多边形共享一条边,应用程序会将它们视为一个多边形?
  • 我不确定是什么问题。如果您的点击位于您正在测试的线段的左侧,该函数应该返回 true。您需要在多边形中的每组相邻点上运行此函数,并收集此函数返回 true 的次数。
  • Polyline怎么办?
  • @MuhammadBabar 我会在单独的线程上问这个问题。有几种方法可以解决这个问题。这很棘手,因为需要一个可点击的区域缓冲区(用户准确点击在线的几率非常小)
【解决方案2】:

Google 地图支持库现在有一个静态方法可以为您执行此检查:

PolyUtil.containsLocation(LatLng point, List<LatLng>polygon, boolean geodesic);

虽然文档没有在指南中明确提到它,但方法在那里

Maps Support Library docs

【讨论】:

  • 这是更准确的方法。这真的很有魅力。欣赏这个答案。应该相信这种方法来自 Google Map Utility 本身。
【解决方案3】:

使用 release of Google Play Services 8.4.0,Maps API 支持将 OnPolygonClickListener 添加到多边形。 polygonspolylinesoverlays 都支持类似的事件。

您只需要调用GoogleMap.setOnPolygonClickListener(OnPolygonClickListener listener) 进行设置,并相应地为其他侦听器(setOnPolylineClickListener,&c):

map.setOnPolygonClickListener(new GoogleMap.OnPolygonClickListener() {  
    @Override  
    public void onPolygonClick(Polygon polygon) {  
        // Handle click ...  
    }  
});  

虽然有点晚,但它很好地解决了这个用例。

【讨论】:

  • 如何检测点击了哪个多边形?
  • @Delta 它是您在侦听器中收到的多边形。
  • 我为包含 ID 的多边形创建了一个类,但我无法为多边形设置 ID,那么如何找出多边形的 ID?
  • @Delta7 您可以为参考创建一个 Map,然后添加您添加到地图的任何多边形。这样您就可以进行查找以找到关联的 id。
  • 你能从多边形中检索点击的坐标吗?
【解决方案4】:

虽然user1504495在我使用它时已经简短地回答了。但不要使用整个 Map Utility Library 使用这种方法。

从您的活动类中相应地传递参数:

if (area.containsLocation(Touchablelatlong, listLatlong, true))
                isMarkerINSide = true;
            else
                isMarkerINSide = false;

并将以下内容放在单独的类中:

/**
     * Computes whether the given point lies inside the specified polygon.
     * The polygon is always cosidered closed, regardless of whether the last point equals
     * the first or not.
     * Inside is defined as not containing the South Pole -- the South Pole is always outside.
     * The polygon is formed of great circle segments if geodesic is true, and of rhumb
     * (loxodromic) segments otherwise.
     */
    public static boolean containsLocation(LatLng point, List<LatLng> polygon, boolean geodesic) {
        final int size = polygon.size();
        if (size == 0) {
            return false;
        }
        double lat3 = toRadians(point.latitude);
        double lng3 = toRadians(point.longitude);
        LatLng prev = polygon.get(size - 1);
        double lat1 = toRadians(prev.latitude);
        double lng1 = toRadians(prev.longitude);
        int nIntersect = 0;
        for (LatLng point2 : polygon) {
            double dLng3 = wrap(lng3 - lng1, -PI, PI);
            // Special case: point equal to vertex is inside.
            if (lat3 == lat1 && dLng3 == 0) {
                return true;
            }
            double lat2 = toRadians(point2.latitude);
            double lng2 = toRadians(point2.longitude);
            // Offset longitudes by -lng1.
            if (intersects(lat1, lat2, wrap(lng2 - lng1, -PI, PI), lat3, dLng3, geodesic)) {
                ++nIntersect;
            }
            lat1 = lat2;
            lng1 = lng2;
        }
        return (nIntersect & 1) != 0;
    }

    /**
     * Wraps the given value into the inclusive-exclusive interval between min and max.
     * @param n   The value to wrap.
     * @param min The minimum.
     * @param max The maximum.
     */
    static double wrap(double n, double min, double max) {
        return (n >= min && n < max) ? n : (mod(n - min, max - min) + min);
    }

    /**
     * Returns the non-negative remainder of x / m.
     * @param x The operand.
     * @param m The modulus.
     */
    static double mod(double x, double m) {
        return ((x % m) + m) % m;
    }

    /**
     * Computes whether the vertical segment (lat3, lng3) to South Pole intersects the segment
     * (lat1, lng1) to (lat2, lng2).
     * Longitudes are offset by -lng1; the implicit lng1 becomes 0.
     */
    private static boolean intersects(double lat1, double lat2, double lng2,
                                      double lat3, double lng3, boolean geodesic) {
        // Both ends on the same side of lng3.
        if ((lng3 >= 0 && lng3 >= lng2) || (lng3 < 0 && lng3 < lng2)) {
            return false;
        }
        // Point is South Pole.
        if (lat3 <= -PI/2) {
            return false;
        }
        // Any segment end is a pole.
        if (lat1 <= -PI/2 || lat2 <= -PI/2 || lat1 >= PI/2 || lat2 >= PI/2) {
            return false;
        }
        if (lng2 <= -PI) {
            return false;
        }
        double linearLat = (lat1 * (lng2 - lng3) + lat2 * lng3) / lng2;
        // Northern hemisphere and point under lat-lng line.
        if (lat1 >= 0 && lat2 >= 0 && lat3 < linearLat) {
            return false;
        }
        // Southern hemisphere and point above lat-lng line.
        if (lat1 <= 0 && lat2 <= 0 && lat3 >= linearLat) {
            return true;
        }
        // North Pole.
        if (lat3 >= PI/2) {
            return true;
        }
        // Compare lat3 with latitude on the GC/Rhumb segment corresponding to lng3.
        // Compare through a strictly-increasing function (tan() or mercator()) as convenient.
        return geodesic ?
                tan(lat3) >= tanLatGC(lat1, lat2, lng2, lng3) :
                mercator(lat3) >= mercatorLatRhumb(lat1, lat2, lng2, lng3);
    }

    /**
     * Returns tan(latitude-at-lng3) on the great circle (lat1, lng1) to (lat2, lng2). lng1==0.
     * See http://williams.best.vwh.net/avform.htm .
     */
    private static double tanLatGC(double lat1, double lat2, double lng2, double lng3) {
        return (tan(lat1) * sin(lng2 - lng3) + tan(lat2) * sin(lng3)) / sin(lng2);
    }

    /**
     * Returns mercator Y corresponding to latitude.
     * See http://en.wikipedia.org/wiki/Mercator_projection .
     */
    static double mercator(double lat) {
        return log(tan(lat * 0.5 + PI/4));
    }

    /**
     * Returns mercator(latitude-at-lng3) on the Rhumb line (lat1, lng1) to (lat2, lng2). lng1==0.
     */
    private static double mercatorLatRhumb(double lat1, double lat2, double lng2, double lng3) {
        return (mercator(lat1) * (lng2 - lng3) + mercator(lat2) * lng3) / lng2;
    } 

【讨论】:

  • 这个答案对我有用。是否可以添加公差?因此,如果给定的位置在多边形外 50 米处,它仍然会验证它是否有效?
【解决方案5】:

这是一个完整的工作示例,用于了解多边形上是否发生了触摸。有些答案比他们需要的更复杂。此解决方案使用“android-maps-utils”

// compile 'com.google.maps.android:android-maps-utils:0.3.4'
private ArrayList<Polygon> polygonList = new ArrayList<>();

private void addMyPolygons() {
    PolygonOptions options = new PolygonOptions();
    // TODO: make your polygon's however you want
    Polygon polygon = googleMap.addPolygon(options);
    polygonList.add(polygon);
}

@Override
public void onMapClick(LatLng point) {
    boolean contains = false;
    for (Polygon p : polygonList) {
        contains = PolyUtil.containsLocation(point, p.getPoints(), false);
        if (contains) break;
    }
    Toast.makeText(getActivity(), "Click in polygon? "
            + contains, Toast.LENGTH_SHORT).show();
}

@Override
protected void onMapReady(View view, Bundle savedInstanceState) {
    googleMap.setOnMapClickListener(this);
    addMyPolygons();
}

【讨论】:

    【解决方案6】:

    只是为了保持一致性 - 当用户点击多边形(或其他叠加层)时不会调用 onMapClick,它在 javadoc 中有所提及。

    我做了一个解决方法,在 MapFragment 处理它们之前拦截点击事件,并将点投影到地图坐标并检查该点是否在任何多边形内,如其他答案中所建议的那样。

    查看更多详情here

    【讨论】:

    猜你喜欢
    • 2015-06-16
    • 2012-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 2013-05-29
    • 2016-03-31
    • 1970-01-01
    相关资源
    最近更新 更多