基于turf在多边形内随机生成点

实现思路:1)获取多边形矩形框范围,2)在多边形矩形框范围内随机生成一个任意点;3)判断生成的点是否在多边形面内,如果在则结束,否则,重复2 3步骤,支到判断点在多边形面内为真结束。

//获取楼多边形的范围
    var bounds = JSON.parse(selects[1].options[selects[1].selectedIndex].getAttribute("data-bounds"));
    console.log(bounds);
    //适配范围格式
    var arr = [];
    for (var i = 0; i < bounds.length; i++) {
        console.log(bounds[i]);
        arr.push(bounds[i]);
    }
    console.log(bounds[0]);
    //首尾坐标串应该一致
    arr.push(bounds[0]);
    var polygon1 = new AMap.Polygon({
        bubble: true,
        fillOpacity: 0.4,
        strokeWeight: 1,
        path: bounds,
        map: map,
        strokeColor: "#0000ff",
        fillColor: "#0000ff"
    });
    //获取楼的矩形范围
    var sz = polygon1.getBounds(); 
    console.log(sz)
    var sw = sz.getSouthWest();
    var ne = sz.getNorthEast();
    var minlng = sw.lng;
    var minlat = sw.lat;
    var maxlng = ne.lng;
    var maxlat = ne.lat; 		

    //随机生成一个矩形范围内的点;
    var points = turf.randomPoint(1, { bbox: [minlng, minlat, maxlng, maxlat] });
    console.log(points);
    var coordinates = points.features[0].geometry.coordinates;
    console.log(coordinates)
    var point = turf.point([coordinates[0], coordinates[1]]);
    console.log(point)
    //楼的多边形
    var py = turf.polygon([arr]);
    console.log(py)
    //判断生成的随机点是否在面内
    var ptsIn = turf.booleanPointInPolygon(point, py);
    console.log(ptsIn);
    //判断随机生成的点是否在面内,如果不在继续生成随机点并判断。
    //循环次数
    var count = 0;
    while (!ptsIn) {
        points = turf.randomPoint(1, { bbox: [minlng, minlat, maxlng, maxlat] });
        console.log(points);
        coordinates = points.features[0].geometry.coordinates;
        point = turf.point([coordinates[0], coordinates[1]]);
        ptsIn = turf.booleanWithin(point, py);
        console.log(ptsIn);  
        count++;
    }
    console.log(count);
    var pos = new AMap.LngLat(coordinates[0], coordinates[1]);
    var marker = new AMap.Marker({ map: map, position: pos });

 

你可能感兴趣的:(高德地图)