一、基本概念
交互式绘制的两个基本概念
- 画布
- 画笔
画布就是一个数据源,加载到矢量图层。
画笔就是交互式控件ol.interaction.Draw
二、操作步骤
1、创建画布(矢量图层,数据源)2、创建画笔(交互式控件)
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script src="../../lib/include-openlayers-local.js"></script><script src="../../js/Tian.js"></script></head><body><div id="map_container"></div><script>const map = new ol.Map({target:"map_container",layers:[TianDiMap_vec,TianDiMap_cva],view:new ol.View({center:[114,30],projection:'EPSG:4326',zoom:4})})/* 1、创建画布 */const source = new ol.source.Vector({wrapX:false})const layer = new ol.layer.Vector({source:source})map.addLayer(layer)/* 2、新建画笔 */let draw = new ol.interaction.Draw({source:source,type:'Point'})map.addInteraction(draw);draw.on("drawend",function(e){console.log("绘制完成")})</script></body></html>
2-1、点击事件-激活画笔
关键步骤创建画笔和激活画笔
# 创画笔// 1、 创建画笔const draw = new ol.interaction.Draw({// 在哪个画布上绘制source: source,// 绘制的类型type: 'Point',})
2、 激活画笔map.addInteraction(draw)
<body><button id="addPoint" onclick="addPoint()">激活</button><button id="exit" onclick="exit()">退出</button><button id="reset" onclick="reset()">清除</button><div id="map_container"></div><script>const map = new ol.Map({target: 'map_container',layers: [TianDiMap_vec, TianDiMap_cva],view: new ol.View({projection: 'EPSG:4326',center: [0, 0],zoom: 2,}),})// 一. 创建画布// 1-1、创建矢量数据源let source = new ol.source.Vector({wrapX: false})// 1-2、创建矢量图层let vector = new ol.layer.Vector({source: source})// 1-3、 添加失量图层到map对象中map.addLayer(vector)// 二. 创建画笔let draw = nullfunction addPoint() {draw = new ol.interaction.Draw({// 在哪个画布上绘制source: source,// 绘制的类型type: 'Point',})map.addInteraction(draw)// 三. 监听绘制完成事件draw.on('drawend', function (e) {console.log('绘制完成')})}</script></body>
2-2、移除画笔
map.removeInteraction()
function exit() {map.removeInteraction(draw)}
2-3、清除
function reset(){source.clear();}
2-4、代码优化
<body><button onclick="active()">激活画笔</button><button onclick="remove()">移除画笔</button><button onclick="reset()">清除</button><div id="map_container"></div><script>var map = new ol.Map({target:"map_container",layers:[gaode],view:new ol.View({projection:'EPSG:4326',center:[114.30,30.50],zoom:4})})/* 1、创建画布 */var source = new ol.source.Vector({wrapX:false})var layer = new ol.layer.Vector({source})map.addLayer(layer)/* 2、激活画笔 */let draw;function active(){draw = new ol.interaction.Draw({type:"Point",source})map.addInteraction(draw);}function remove(){map.removeInteraction(draw);}function reset(){source.clear();}</script></body>
