文章目录
- 一、前言
- 二、代码实现
- 三、总结
一、前言
图层探查,即对置于地图下方的图层进行一定范围的探查,以便用户查看到不易察觉的地理地况。本文基于OpenLayers3,实现地图探查的功能。
二、代码实现
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>图层探查功能实现</title><link href="../../libs/ol3/ol.css" rel="stylesheet" type="text/css" /><script src="../../libs/ol3/ol.js" type="text/javascript"></script>
</head>
<body><div id="map" class="map" style="width: 100%; height: 95%; position: absolute;"></div><script type="text/javascript">var tdttk = '***' // 天地图认证tkvar TiandiMap_vec = new ol.layer.Tile({title: "天地图矢量图层",source: new ol.source.XYZ({url: "http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=" + tdttk,//parent.TiandituKey()为天地图密钥wrapX: false})});var Tianditu_cva = new ol.layer.Tile({title: "天地图矢量注记图层",source: new ol.source.XYZ({url: "http://t0.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=" + tdttk,//parent.TiandituKey()为天地图密钥wrapX: false})});var TiandiMap_img = new ol.layer.Tile({title: "天地图影像图层",source: new ol.source.XYZ({url: "http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=" + tdttk,//parent.TiandituKey()为天地图密钥wrapX: false})});//设置地图容器放置位置var container = document.getElementById('map');//创建地图容器var map = new ol.Map({layers: [TiandiMap_img, Tianditu_cva, TiandiMap_vec],target: container,view: new ol.View({center: ol.proj.fromLonLat([-109, 46.5]),zoom: 6})});//探查半径var radius = 75;//添加键盘按下事件监听,用来控制探查范围的大小document.addEventListener('keydown', function (evt) {if (evt.which == 38) {radius = Math.min(radius + 5, 150);//map.render();evt.preventDefault();} else if (evt.which == 40) {radius = Math.max(radius - 5, 25);map.render();evt.preventDefault();}});// 实时得到鼠标的像素位置var mousePosition = null;container.addEventListener('mousemove', function (event) {mousePosition = map.getEventPixel(event);map.render();});container.addEventListener('mouseout', function () {mousePosition = null;map.render();});// 在渲染层之前,做剪裁TiandiMap_vec.on('precompose', function (event) {var ctx = event.context;var pixelRatio = event.frameState.pixelRatio;ctx.save();ctx.beginPath();if (mousePosition) {//只显示一个围绕着鼠标的圆圈ctx.arc(mousePosition[0] * pixelRatio, mousePosition[1] * pixelRatio, radius * pixelRatio, 0, 2 * Math.PI);ctx.lineWidth = 5 * pixelRatio;ctx.strokeStyle = 'rgba(0,0,0,0.5)';ctx.stroke();}ctx.clip();});// 呈现层后,恢复画布的背景TiandiMap_vec.on('postcompose', function (event) {var ctx = event.context;ctx.restore();});</script>
</body>
</html>
三、总结
以上为基于openlayer3 实现地图探查功能的简单案例,希望对您有帮助~