nearestPointOnLine函数用于计算一条线段上距离指定点最近的点。
turf.nearestPointOnLine(line, pt, options)
line:必填,表示要查询的线段,可以是Turf支持的各种GeoJSON格式的数据。pt:必填,表示要查询的点,可以是Turf支持的各种GeoJSON格式的数据。options:选填,表示可选项参数,是一个对象。options中可包括以下参数:
units:选填,表示查询结果中距离的单位,可以是以下单位字符串之一:
degrees:度数
radians:弧度
miles:英里
kilometers:千米
feet:英尺
meters:米
默认值为meters。
mercator:选填,表示线段是否基于Mercator投影计算,在大地球和低纬度时,可能会影响计算精度。默认值为false。
该函数会返回一个包含以下属性的对象:
type:表示返回的几何类型,固定为Feature。properties:表示返回的属性信息,一个对象,包括以下属性:
index:距离最近的点在线段上的位置。distanceToPoint:距离最近的点与查询点之间的距离。nearestPoint:距离最近的点的坐标。geometry:表示返回的几何信息,一个Point类型的Feature,表示距离最近的点的坐标。const line = turf.lineString([[0, 0], [10, 10]]);
const pt = turf.point([2, 2]);
const nearestPt = turf.nearestPointOnLine(line, pt);
console.log(nearestPt);
//输出: {
// type: 'Feature',
// properties: {
// index: 0.2,
// distanceToPoint: 2.8284271247461903,
// nearestPoint: [1.9999999999999998, 1.9999999999999998]
// },
// geometry: {
// type: 'Point',
// coordinates: [1.9999999999999998, 1.9999999999999998]
// }
// }
如果传入的参数不符合要求,该函数会抛出异常,错误消息为相应的提示信息。