用turf.js求多个点的外包多边形

发布于:2023-01-04 ⋅ 阅读:(427) ⋅ 点赞:(0)

概述

最近有个需求就是求多个点的外包多边形,看了下turf.js可以实现,在此记录分享一下。

实现后效果

image.png

实现

可以通过两种方式实现:turf.convexturf.tinturf.convex可直接计算结果,turf.tin稍微麻烦一点,先创建不规则三角网,再通过turf.union合并得到结果。下面通过ol做一示例。

// 通过geojson获取features
function getFeatures(geojson) {
    let features = (new ol.format.GeoJSON()).readFeatures(geojson);
    features.forEach(f => {
      f.setGeometry(f.getGeometry().transform('EPSG:4326', "EPSG:3857"))
    })
    return features
}
// turf.convex
 fetch('./data/college.geojson').then(res => res.json()).then(res => {
    let features = [...getFeatures(res)]
    res = turf.convex(res);
    features = [...features, ...getFeatures(res)]
    vectorSource.addFeatures(features)
  })

// turf.tin
 fetch('./data/college.geojson').then(res => res.json()).then(res => {
    let features = [...getFeatures(res)]
    res = turf.tin(res)
    res = res.features
    let _res = res.shift()
    while (res.length > 0) {
      const r = res.shift()
      _res = turf.union(_res, r)
    }
    features = [...features, ...getFeatures(_res)]
    vectorSource.addFeatures(features)
  })
本文含有隐藏内容,请 开通VIP 后查看