mapbox-gl开发:动态画线标绘
在mapbox-gl地图上,实现动态画线的效果,点击左键增加画线的点,鼠标移动,实现线随着鼠标移动位置的效果,点击右键结束画线。
mapbox-gl接口实现标绘数据存储在geojson数据中,通过添加数据源、修改数据源,实现地图上的标绘数据实时更新。
添加geojson数据源:
this.map.addSource(this.sourceid, {
type: 'geojson',
data: this.geojsondata
})
添加线标绘图层,设置线标绘的属性信息:
this.map.addLayer({
id: this.linelayerid,
type: 'line',
source: this.sourceid,
layout: {
'line-cap': 'round',
'line-join': 'round'
},
paint: {
'line-color': '#f00',
'line-width': 2
},
filter: ['in', '$type', 'LineString']
})
鼠标动态移动事件,线的终点随着鼠标移动
this.mapmousemovefunc = function (e) {
const _editfeature = scope.geojsondata.features[scope.getEditFeatureid()]
_editfeature.geometry.coordinates.splice(_editfeature.geometry.coordinates.length - 1, 1, [e.lngLat.lng, e.lngLat.lat])
scope.map.getSource(scope.sourceid).setData(scope.geojsondata)
}
鼠标点击事件,分为初次点击和之后点击的事件
this.mapclickfunc = function (e) {
if (_isfirst) {
再次点击鼠标,修改最后一个点,并新增点
const _editfeature = scope.geojsondata.features[scope.getEditFeatureid()]
_editfeature.geometry.coordinates.splice(_editfeature.geometry.coordinates.length - 1, 1, [e.lngLat.lng, e.lngLat.lat])
_editfeature.geometry.coordinates.push([e.lngLat.lng, e.lngLat.lat])
let _centerpos = turf.centroid(scope.geojsondata)
_editfeature.properties.centerpos = _centerpos.geometry.coordinates
scope.map.getSource(scope.sourceid).setData(scope.geojsondata)
} else {
初次点击鼠标,创建线数据
_isfirst = true
scope.editfeatureid = scope.createuuid()
scope.geojsondata.features.push({
type: 'Feature',
geometry: {
type: 'LineString',
coordinates: [
[e.lngLat.lng, e.lngLat.lat],
[e.lngLat.lng + 0.000001, e.lngLat.lat]
]
},
properties: {
id: scope.editfeatureid,
sourceid: scope.sourceid,
isdraw: true,
centerpos: [e.lngLat.lng, e.lngLat.lat],
color: '#f00',
opacity: 0.7
}
})
scope.map.on('mousemove', scope.mapmousemovefunc)
}
}
//增加鼠标点击,右键结束标绘事件
this.map.on('click', this.mapclickfunc)
this.maprightclickfunc = function () {
scope.stop()
}
this.map.on('contextmenu', this.maprightclickfunc)
