抽稀算法-Douglas-Peuker

1,183 阅读1分钟

有时候gis采集的点过多渲染时会造成资源浪费,需要抽稀处理,Douglas-Peuker是比较常用的算法,具体实现如下:

//points:[turf.point],distance:单位km
const sparse=(points,distance)=>{
    const list=[0,points.length-1]
    //获取曲线到直线距离最大的点
    const getMaxDistanceItem=(start,end)=>{
        const lineString=turf.lineString([points[start],points[end]])
        let pos=-1,max=0
        for(let i=start;i<end;i++){
            const current=turf.pointToLineDistance(turf.point(points[i]),lineString)
            if(current>max)[pos,max]=[i,current]
        }
        return [pos,max]
    }
    //递归处理所有的线段
    const sparseFn=(start,end)=>{
        const [pos,max]=getMaxDistanceItem(start,end)
        if(max>distance)list.push(pos),sparseFn(start,pos),sparseFn(pos,end)
    }    
    sparseFn(list[0],list[1])
    //将索引转换为point
    return list.sort().map(i=>points[i])
}

抽稀前

image.png

抽稀后

image.png