2014-04-04 55 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

相關問題