工具函数
坐标转换
BicMap 内置坐标转换工具,用于机器人坐标系(笛卡尔坐标)与地图坐标系(WGS84 经纬度)之间的互转。
js
import { MapUtils } from '@x-humanoid-cloud/bic-map'MapUtils.GPSToCartesian(params)
将 WGS84 经纬度坐标转换为笛卡尔坐标(米)。
js
const cartesian = MapUtils.GPSToCartesian({
longitude: 116.3912,
latitude: 39.9073,
scale: 1, // 缩放系数,默认 1
zoomFactor: 1 // 缩放因子,默认 1
})
// 返回: { x: number, y: number }MapUtils.CartesianToGPS(params)
将笛卡尔坐标转换回 WGS84 经纬度。
js
const gps = MapUtils.CartesianToGPS({
x: cartesian.x,
y: cartesian.y,
scale: 1,
zoomFactor: 1
})
// 返回: { longitude: number, latitude: number }在机器人标记中使用
js
bicMap.addRobotMarkers(map, robots, {
svgPath: '/robot.svg',
GPSToCartesian: (lng, lat) => {
return MapUtils.GPSToCartesian({ longitude: lng, latitude: lat })
}
})几何计算
BicMap 内置 @turf/turf,通过 bicMap.turf 访问所有 turf 函数。
js
// 计算多边形面积(平方米)
const areaSqM = bicMap.turf.area(geoJsonFeature)
// 计算两点距离
const distKm = bicMap.turf.distance(
bicMap.turf.point([116.39, 39.90]),
bicMap.turf.point([116.42, 39.93]),
{ units: 'kilometers' }
)
// 计算几何中心点
const center = bicMap.turf.center(geoJsonFeature)
// center.geometry.coordinates → [lng, lat]
// 计算线段长度(周长)
const lengthKm = bicMap.turf.length(geoJsonLineString, { units: 'kilometers' })
// 判断点是否在多边形内
const isInside = bicMap.turf.booleanPointInPolygon(
bicMap.turf.point([116.4, 39.9]),
polygonFeature
)
// 生成缓冲区
const buffered = bicMap.turf.buffer(feature, 0.5, { units: 'kilometers' })
// 计算交集
const intersection = bicMap.turf.intersect(polygon1, polygon2)TIP
bicMap.turf 是完整的 @turf/turf@7.3.5 对象,支持所有 Turf.js API。详细文档参考 turfjs.org。
常用工具代码示例
计算绘制区域信息
js
bicMap.enablePolygonDrawing(map, {
onDrawComplete: (polygon, info) => {
// 方法一:使用 info 对象(BicMap 已计算好)
console.log(`面积: ${info.area.toFixed(4)} km²`)
console.log(`周长: ${info.perimeter.toFixed(4)} km`)
// 方法二:手动使用 turf 计算
const areaSqM = bicMap.turf.area(polygon)
const areaHa = areaSqM / 10000
console.log(`面积: ${areaHa.toFixed(2)} 公顷`)
}
})批量坐标转换
js
// 机器人路径点转地图坐标
const robotPath = [
{ x: 0, y: 0 },
{ x: 5.2, y: 3.1 },
{ x: 10.4, y: 6.8 }
]
const mapCoords = robotPath.map(({ x, y }) => {
const gps = MapUtils.CartesianToGPS({ x, y, scale: 1 })
return [gps.longitude, gps.latitude]
})
