mapbox-gl開發(fā):動態(tài)畫線標(biāo)繪
在mapbox-gl地圖上,實現(xiàn)動態(tài)畫線的效果,點(diǎn)擊左鍵增加畫線的點(diǎn),鼠標(biāo)移動,實現(xiàn)線隨著鼠標(biāo)移動位置的效果,點(diǎn)擊右鍵結(jié)束畫線。
mapbox-gl接口實現(xiàn)標(biāo)繪數(shù)據(jù)存儲在geojson數(shù)據(jù)中,通過添加數(shù)據(jù)源、修改數(shù)據(jù)源,實現(xiàn)地圖上的標(biāo)繪數(shù)據(jù)實時更新。
添加geojson數(shù)據(jù)源:
? ? ??this.map.addSource(this.sourceid,?{
? ? ? ? ? ??type:?'geojson',
? ? ? ? ???data:?this.geojsondata
? ?????})
添加線標(biāo)繪圖層,設(shè)置線標(biāo)繪的屬性信息:
? ???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']
? ? })
鼠標(biāo)動態(tài)移動事件,線的終點(diǎn)隨著鼠標(biāo)移動
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)
??}
鼠標(biāo)點(diǎn)擊事件,分為初次點(diǎn)擊和之后點(diǎn)擊的事件
??this.mapclickfunc?=?function?(e)?{
????if?(_isfirst)?{
再次點(diǎn)擊鼠標(biāo),修改最后一個點(diǎn),并新增點(diǎn)
??????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?{
? ?初次點(diǎn)擊鼠標(biāo),創(chuàng)建線數(shù)據(jù)
??????_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)
????}
??}
//增加鼠標(biāo)點(diǎn)擊,右鍵結(jié)束標(biāo)繪事件
this.map.on('click',?this.mapclickfunc)
this.maprightclickfunc?=?function?()?{
????scope.stop()
??}
??this.map.on('contextmenu',?this.maprightclickfunc)
