方案
我正在尝试生成500到1000个随机坐标(纬度,长度),它位于半径1公里的圆内,其中心点位于(5.418680,100.327829)。我试图在PHP中编写代码,但没有这样做,因为我不知道我应该为$ radius提供什么值。
$radius = ?;
$origin_x = 5.420525;
$origin_y = 100.319500;
$angle = deg2rad(mt_rand(0, 359));
$pointRadius = mt_rand(0, $radius);
$point[] = array(
'x' => $origin_x + ($pointRadius * cos($angle)),
'y' => $origin_y + ($pointRadius * sin($angle))
);
我想到了另一种方法。而不是在圆内生成点,我想在正方形边界内生成点,然后应用Haversine大圆距离公式来确定随机生成的点位于1KM半径的圆内。
注意:生成的点可以相互重叠。
请告知,我需要了解我应该采取什么方法。提前谢谢。
答案 0 :(得分:1)
在圆圈范围内创建随机点:
var bounds = circle.getBounds();
map.fitBounds(bounds);
var sw = bounds.getSouthWest();
var ne = bounds.getNorthEast();
for (var i = 0; i < 100; i++) {
// create a random point inside the bounds
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.spherical.computeDistanceBetween(point,circle.getCenter()) < circle.getRadius()) {
createMarker(map, point,"marker "+i);
// break; if only need one point
} // else nothing.
使用Google Maps Javascript API v3的示例:
var circle;
var infowindow = new google.maps.InfoWindow({});
function initialize() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 4,
center: new google.maps.LatLng(22.7964, 79.8456),
mapTypeId: google.maps.MapTypeId.HYBRID
});
circle = new google.maps.Circle({
center: map.getCenter(),
radius: 1000, // meters
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0000FF",
fillOpacity: 0.26
});
circle.setMap(map);
var bounds = circle.getBounds();
map.fitBounds(bounds);
var sw = bounds.getSouthWest();
var ne = bounds.getNorthEast();
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.spherical.computeDistanceBetween(point, circle.getCenter()) < circle.getRadius()) {
createMarker(map, point, "marker " + i);
// break;
}
}
}
function createMarker(map, point, content) {
var marker = new google.maps.Marker({
position: point,
map: map
});
google.maps.event.addListener(marker, "click", function(evt) {
infowindow.setContent(content + "<br>" + marker.getPosition().toUrlValue(6));
infowindow.open(map, marker);
});
return marker;
}
google.maps.event.addDomListener(window, 'load', initialize);
&#13;
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map" style="width: 530px; height: 500px">
</div>
&#13;
答案 1 :(得分:0)
我会这样做:
我想可能有办法避免在第2步中丢弃,但这可能会使事情方式更复杂,因此对于实际应用我会坚持这一点。