Skip to content

Latest commit

 

History

History
108 lines (99 loc) · 3.33 KB

09-07.md

File metadata and controls

108 lines (99 loc) · 3.33 KB

绘图进阶

前面只是简单的绘制上了一条线,在实际业务中,可能还需要设置绘图时的样式,限制绘制的点的个数,获取绘制的图形的所有坐标等。 在上一节的基础上,以下面这个地图为例,再给大家介绍一下这些方面的更深入的应用。下面绘制这条线的点不能超过4个,在绘制时,样式会和前一节的样式不太一样,在地图上方,会显示当前绘制完的线的所有点的坐标。

<script type="text/javascript" src="../src/ol3.13.1/ol.js" charset="utf-8"></script>
当前绘制线的坐标:
<script type="text/javascript"> var map = new ol.Map({ layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }) ], target: 'map', view: new ol.View({ center: ol.proj.transform( [104, 30], 'EPSG:4326', 'EPSG:3857'), zoom: 10 }) });
// 添加一个绘制的线使用的layer
var lineLayer = new ol.layer.Vector({
	source: new ol.source.Vector(),
	style: new ol.style.Style({
		stroke: new ol.style.Stroke({
			color: 'red',
			size: 1
		})
	})
})
map.addLayer(lineLayer);
var lineDraw = new ol.interaction.Draw({
	type: 'LineString',
	source: lineLayer.getSource(),	// 注意设置source,这样绘制好的线,就会添加到这个source里
	style: new ol.style.Style({
		stroke: new ol.style.Stroke({
			color: '#009933',
			size: 1
		})
	}),
	maxPoints: 4
});

// 监听线绘制结束事件,获取坐标
lineDraw.on('drawend', function(event){
	document.getElementById('points').innerHTML = JSON.stringify(event.feature.getGeometry().getCoordinates());
});

map.addInteraction(lineDraw);
</script>

代码如下,关键代码还是放在最后:

<div style="background-color: #999;"><span>当前绘制线的坐标:</span><span id='points'></span></div>
<div id="map" style="width: 100%"></div>
<script type="text/javascript">
	var map = new ol.Map({
		layers: [
		  new ol.layer.Tile({
		    source: new ol.source.OSM()
		  })
		],
		target: 'map',
		view: new ol.View({
		  center: ol.proj.transform(
		      [104, 30], 'EPSG:4326', 'EPSG:3857'),
		  zoom: 10
		})
	});

	// 添加一个绘制的线使用的layer
	var lineLayer = new ol.layer.Vector({
		source: new ol.source.Vector(),
		style: new ol.style.Style({
			stroke: new ol.style.Stroke({
				color: 'red',
				size: 1
			})
		})
	})
	map.addLayer(lineLayer);
	var lineDraw = new ol.interaction.Draw({
		type: 'LineString',
		source: lineLayer.getSource(),	// 注意设置source,这样绘制好的线,就会添加到这个source里
		style: new ol.style.Style({			// 设置绘制时的样式
			stroke: new ol.style.Stroke({
				color: '#009933',
				size: 1
			})
		}),
		maxPoints: 4	// 限制不超过4个点
	});

	// 监听线绘制结束事件,获取坐标
	lineDraw.on('drawend', function(event){
		// event.feature 就是当前绘制完成的线的Feature
		document.getElementById('points').innerHTML = JSON.stringify(event.feature.getGeometry().getCoordinates());
	});

	map.addInteraction(lineDraw);
</script>

如果需要取消当前绘制,直接用map.removeInteraction(lineDraw)就可以了。