1.在index.html直接引用
<script src="https://unpkg.com/@turf/turf@6.3.0/turf.min.js"></script>
2.需要用的地方直接使用turf对象,turf主要用来空间几何对象关系的计算,点、线、面之间包含、相交等系统运算。
具体使用方法可参考turf.js中文网:https://turfjs.fenxianglu.cn/category/#cdn%E5%BC%95%E5%85%A5
3.判断点是否在多边形范围内
let pt = turf.point([103.30749303102493, 29.789869635742235]);
let coordinates = [...];//多边形数据
let poly;
if(coordinates.length>1){
//解决'Each LinearRing of a Polygon must have 4 or more Positions.'错误
poly = turf.multiPolygon(coordinates);
}else{
poly = turf.polygon(coordinates);
}
let isIncluded = turf.booleanPointInPolygon(pt, poly)
多边形数据格式:
3.获取多边形范围的中心点
let poly;
let coordinates = [...];//多边形数据
if(coordinates.length>1){
//解决'Each LinearRing of a Polygon must have 4 or more Positions.'错误
poly = turf.multiPolygon(coordinates );
}else{
poly = turf.polygon(coordinates );
}
let centerPoint = turf.centerOfMass(poly); //获取多边形得中心点坐标
console.log(centerPoint)
4.获取一系列点和多边形的绝对中心点
let areaArr = areaData.map(item=>item.geometry.coordinates);
let pointArr = pointData.map(item=>item.geometry.coordinates);
let centerPoint;
if(areaArr.length){
centerPoint = turf.centroid(turf.multiPolygon([...areaArr, ...pointArr]))
}else{
centerPoint = turf.center(turf.featureCollection(
pointArr.map(item=>turf.point(item))
))
}
let areaCoordinates = [...];//多边形数据
let pointCoordinates = [...];//点数据
let centerPoint;
if(areaCoordinates.length){//判断是否存在多边形
centerPoint = turf.centroid(turf.multiPolygon([...areaCoordinates , ...pointCoordinates ]))
}else{
centerPoint = turf.center(turf.featureCollection(
pointCoordinates.map(item=>turf.point(item))
))
}
console.log(centerPoint)