2013-01-10 173 views
3

我有這個代碼在這裏試圖解決如果點latLng通過一個多邊形Maps.area尋找一個點是否在一個多邊形

Maps.ui.contains = function(latLng){ 
    //poly.getBounds gets the 'box' around the polygon 
    if(!Maps.ui.getBounds().contains(latLng)) 
     return false; 
    //So we dont need to check t/f, we either set it or we dont 
    var inPolygon = false; 
    var count = 0; 

    Maps.area.getPaths().forEach(function(el0, index0){ 
     var last = el0.getLength() - 1; 
     el0.forEach(function(el1, index1){ 
      count += Maps.ui.ray_intersect_segment(latLng, el1, el0.getAt(last)); 
      last = index1; 
     }); 
    }); 

    if(Maps.area.getPaths().getLength()%2 == 0) 
     return count%2==0; 
    else 
     return count%2!=0; 


} 

var eps = 0.0001; 
var inf = 1e600; 
Maps.ui.ray_intersect_segment = function(point, i1, i2){ 
    var p = point; 
    var segment = (i1.lng() > i2.lng())?[i2, i1]:[i1, i2]; 

    p = (p.lng() == segment[0].lng() || p.lng() == segment[1].lng())?new google.maps.LatLng(p.lng() + eps):p; 

    if(p.lng() < segment[0].lng() || p.lng() > segment[1].lng() || p.lat() > [segment[0].lat(), segment[1].lng()].max()) 
     return 0; 
    if(p.lat() < [segment[0].lat(), segment[1].lat()].min()) 
     return 1; 

    var a = (segment[0].lat() != segment[1].lat())?(segment[1].lng() - segment[0].lng())/(segment[1].lat() - segment[0].lat()):inf; 
    var b = (segment[0].lat() != p.lat()) ? (p.lng() - segment[0].lng())/(p.lat() - segment[0].lat()):inf; 

    return (b > a)?1:0; 
} 

Maps.ui.getBounds = function() { 
    //Lets make a box 
    var bounds = new google.maps.LatLngBounds(); 
    //Get all the points lines of the polly 
    var paths = Maps.area.getPaths(); 
    for (var p = 0; p < paths.getLength(); p++) 
     //To store each path 
     var path = paths.getAt(p); 
     //Now lets expand the box 
     for (var i = 0; i < path.getLength(); i++) 
      //Add each point of the line to the 'box' making it bigger each time 
      bounds.extend(path.getAt(i)); 
    //Reaturn the bounds, this has a contains method so we can check if the latLng is in it. 
    return bounds; 
} 

Array.prototype.max = function() { 
    return Math.max.apply(null, this) 
} 

Array.prototype.min = function() { 
    return Math.min.apply(null, this) 
} 

但我似乎無法解決它。對於一個簡單的三角形或方形它完美的作品,但是當我們到了這樣的事情這是行不通的,因爲我們無法弄清楚count是否應爲偶數或奇數

enter image description here

+0

你的多邊形是否總是凸的? – cppguy

回答

0

這是一個非常地理信息系統的標準問題。有幾個「標準」算法可以解決這個問題。下面的鏈接提到了其中的一些,並提供了一個示例。請注意,算法傾向於在邊緣情況下分解,例如當多邊形跨越極點和子午線等極端經度/緯度邊界時。

Polygon Algorithms

相關問題