概述
最近有个需求就是求多个点的外包多边形,看了下turf.js
可以实现,在此记录分享一下。
实现后效果
实现
可以通过两种方式实现:turf.convex
和turf.tin
,turf.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)
})