2014-09-24 78 views
12

按我的要求,我在下面的圖片中顯示谷歌地圖繪製多邊形。(使用地圖V2)enter image description here確定是否點在多邊形

現在我需要顯示一個警告,當用戶輸入特定的多邊形。

如何識別我的當前位置是否在多邊形中。 (需要優化的方式,無需耗盡電池)

在此先感謝。

+0

你在這裏使用地理圍欄? – Ranjit 2014-09-24 10:25:13

+0

不是。我剛剛使用PolygonOptions繪製了該多邊形。尋找一種最佳方式來識別當前位置是否在該多邊形中。 – Supriya 2014-09-24 10:28:33

+0

您可以使用Geofence。 http://developer.android.com/training/location/geofencing.html – Ranjit 2014-09-24 10:30:02

回答

17

剛試過光線投射算法識別多邊形點。這工作完美。

參考http://en.wikipedia.org/wiki/Point_in_polygon的光線投射

private boolean isPointInPolygon(LatLng tap, ArrayList<LatLng> 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(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 > 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; 
    } 
+0

它對我非常有幫助,謝謝!!! @supriya – Manish 2016-08-25 12:59:57

+0

你的算法總是返回false,爲什麼? – ofskyMohsen 2018-01-07 10:58:27

2

請參考以下鏈接

Polygon Touch detection Google Map API V2

它的光線投射算法,它可以幫助你:)

關於算法的簡要說明:

水平線是從你的觀點吸引到如果它在奇數次與多邊形的邊相交,則該點在多邊形的內部,否則在外:)

這些wiki鏈接會給你全面的瞭解:

http://en.wikipedia.org/wiki/Point_in_polygon

http://rosettacode.org/wiki/Ray-casting_algorithm

+0

試試這個。謝謝:) – Supriya 2014-09-24 11:14:06

+0

爲我的少數測試工作。檢查論文。 :)謝謝 – Supriya 2014-09-24 11:33:38

9

的論文,我發現光線投射方法不可靠的,但我最終使用從谷歌地圖的PolyUtil

您需要依賴compile 'com.google.maps.android:android-maps-utils:0.5'

,然後方法看起來像這樣

PolyUtil.containsLocation(userLocation, polyPointsList, false); 

編輯

這是這種方法在源代碼中發現的描述

單位計算給定點是否位於指定的多邊形內。無論最後一個點是否等於第一個,多邊形總是被視爲關閉。裏面被定義爲不包含南極 - 南極總是在外面。如果測地線爲真,則多邊形由大圓段形成,否則由多邊形(洛索酸)段形成。

+0

爲什麼最後一個參數爲false?這個參數是什麼? – Virat18 2017-09-20 07:53:40

+0

我已經添加了方法的描述,因爲我在源代碼中找到它 – DoruChidean 2017-09-20 08:24:39

+0

謝謝!真棒回答! – Virat18 2017-09-20 09:57:02

相關問題