绘制功能和面积长度测算
- 绘制功能
需要引入插件 mapbox-gl-draw.js,可以通过cnd或者下载源码引入,这里用npm的方式
yarn add @mapbox/mapbox-gl-draw
import MapboxDraw from '@mapbox/mapbox-gl-draw'
let draw = new MapboxDraw() // 需要在地图加载完成之后添加,如果地图还没load结束,功能不生效
map.addControl(draw, 'top-left') // 这里如果需要自定义,通过样式隐藏控件,通过js实现控件的点击事件,例如$('.mapbox-gl-draw_line').trigger('click')
// 绘制时候触发的事件,实现绘制后的功能
map.on('draw.create', (e) => {
console.log('e: ', e)
})
map.on('draw.update', (e) => {
console.log('e: ', e)
})
// 修改绘制的样式,只需要设置对应图层的样式就行
const drawType = [
{
id: 'gl-draw-line-active.cold',
name: '绘制线结束'
},
{
id: 'gl-draw-polygon-stroke-active.cold',
name: '绘制面结束'
},
{
id: 'gl-draw-line-inactive.hot',
name: '绘制线结束'
},
{
id: 'gl-draw-line-inactive.cold',
name: '绘制面结束'
},
{
id: 'gl-draw-line-active.hot',
name: '绘制第一条线'
},
{
id: 'gl-draw-polygon-stroke-active.hot',
name: '拉伸时'
},
{
id: 'gl-draw-polygon-stroke-inactive.hot',
name: '移除后图层'
}
]
- 面积长度测算
通过turf工具计算或者通过超图提供的服务
通过turf
// 长度
let line = turf.lineString(coordinates)
let len = turf.length(line)
alert(len + 'km')
// 面积
let polygon = turf.polygon(coordinates)
let area = turf.area(polygon)
alert(area + '平方米')
超图提供的服务
import { MeasureParameters, Unit, MeasureService } from '@supermap/iclient-mapboxgl'
// 设置量算服务参数
let measureParam = new MeasureParameters()
// 设置要量算的矢量对象({Line}或{Polygon}),geometry可以通过直接初始化的方法获取
measureParam.geometry = e.features[0].geometry
measureParam.unit = Unit.METER
let url = "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World";
// 初始化服务类,设置服务请求关键参数
let measureService = new MeasureService(url)
// 提交服务请求,传递服务查询参数,获取返回结果并按照用户需求进行处理
// 长度
measureService.measureDistance(measureParam).then(function (serviceResult) {
// 获取服务器返回的结果
let { result } = serviceResult
console.log('result: ', result)
})
// 面积
new MeasureService(url).measureArea(areaMeasureParam).then(function (serviceResult) {
// 获取服务器返回的结果
let { result } = serviceResult
console.log('result: ', result)
})