2014-04-04 26 views

回答

5

这样做的一种方法。这将计算多边形的边界,然后猜测边界内的一个随机点,如果点包含在多边形中,它将在那里放置一个标记。

// calculate the bounds of the polygon 
var bounds = new google.maps.LatLngBounds(); 

for (var i=0; i < polygon.getPath().getLength(); i++) { 
    bounds.extend(polygon.getPath().getAt(i)); 
} 

var sw = bounds.getSouthWest(); 
var ne = bounds.getNorthEast(); 

// Guess 100 random points inside the bounds, 
// put a marker at the first one contained by the polygon and break out of the loop 
for (var i = 0; i < 100; i++) { 
    var ptLat = Math.random() * (ne.lat() - sw.lat()) + sw.lat(); 
    var ptLng = Math.random() * (ne.lng() - sw.lng()) + sw.lng(); 
    var point = new google.maps.LatLng(ptLat,ptLng); 
    if (google.maps.geometry.poly.containsLocation(point,polygon)) { 
    var marker = new google.maps.Marker({position:point, map:map}); 
    break; 
    } 
} 

working fiddle

working fiddle with up to 100 random points

相关问题