专栏首页跟牛老师一起学WEBGISOpenlayers3中实现地图的切割

Openlayers3中实现地图的切割

概述:

本文讲述如何在Openlayers3中结合canvas实现对地图的切割。

效果:

全图

切割北京区域

切割河北区域

实现:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>Ol3 wms</title>
	<link rel="stylesheet" type="text/css" href="../../../plugin/ol3/css/ol.css"/>
	<style type="text/css">
		body, #map {
			border: 0px;
			margin: 0px;
			padding: 0px;
			width: 100%;
			height: 100%;
			font-size: 13px;
		}
	</style>
	<script type="text/javascript" src="../../../plugin/ol3/build/ol-debug.js"></script>
	<script type="text/javascript" src="../../../plugin/jquery/jquery-1.8.3.js"></script>
	<script type="text/javascript">
		function init(){
			var bounds = [73.4510046356223, 18.1632471876417,
				134.976797646506, 53.5319431522236];
            var vec_c = getTdtLayer("vec_c");
            var cva_c = getTdtLayer("cva_c");
			var map = new ol.Map({
				controls: ol.control.defaults({
					attribution: false
				}),
				target: 'map',
				layers: [vec_c, cva_c],
				view: new ol.View({
					projection: 'EPSG:4326'
				})
			});
			map.getView().fit(bounds, map.getSize());

            function getTdtLayer(lyr){
                var url = "http://t0.tianditu.com/DataServer?T="+lyr+"&X={x}&Y={y}&L={z}";
                var projection = ol.proj.get("EPSG:4326");
                var projectionExtent = [ -180, -90, 180, 90 ];
                var maxResolution = (ol.extent.getWidth(projectionExtent) / (256 * 2));
                var resolutions = new Array(16);
                var z;
                for (z = 0; z < 16; ++z) {
                    resolutions[z] = maxResolution / Math.pow(2, z);
                }
                var tileOrigin = ol.extent.getTopLeft(projectionExtent);
                var layer = new ol.layer.Tile({
                    extent: [ -180, -90, 180, 90 ],
                    source: new ol.source.TileImage({
                        tileUrlFunction: function(tileCoord) {
                            var z = tileCoord[0]+1;
                            var x = tileCoord[1];
                            var y = -tileCoord[2]-1;
                            var n = Math.pow(2, z + 1);
                            x = x % n;
                            if (x * n < 0) {
                                x = x + n;
                            }
                            return url.replace('{z}', z.toString())
                                .replace('{y}', y.toString())
                                .replace('{x}', x.toString());
                        },
                        projection: projection,
                        tileGrid: new ol.tilegrid.TileGrid({
                            origin: tileOrigin,
                            resolutions: resolutions,
                            tileSize: 256
                        })
                    })
                });
                return layer;
            }

            $.get("data/province.geojson",null,function(result){
                var image = new ol.style.Circle({
                    radius: 5,
                    fill: null,
                    stroke: new ol.style.Stroke({color: 'red', width: 1})
                });
                var styles = new ol.style.Style({
                    stroke: new ol.style.Stroke({
                        color: 'blue',
                        width: 2
                    }),
                    fill: new ol.style.Fill({
                        color: 'rgba(0, 0, 255, 0)'
                    })
                });
                var vectorSource = new ol.source.Vector({
                    features: (new ol.format.GeoJSON()).readFeatures(result)
                });
                var vector = new ol.layer.Vector({
                    source: vectorSource,
                    style: styles
                });
                map.addLayer(vector);

                var _styles = new ol.style.Style({
                    stroke: new ol.style.Stroke({
                        color: '#00ffff',
                        lineDash: [4],
                        width: 3
                    }),
                    fill: new ol.style.Fill({
                        color: 'rgba(0, 0, 255, 0.1)'
                    })
                });
                var select = new ol.interaction.Select({
                    condition: ol.events.condition.click,
                    style: _styles
                });
                map.addInteraction(select);

                var highlight;
                select.on('select', function (e) {
                    var feature = e.target.getFeatures().item(0);
                    if (feature) {
                        highlight = feature;
                        var _coord = feature.getGeometry().getCoordinates();
                        console.log(_coord);
                        map.render();
                        map.on('precompose',clip)
                    }
                });

                var center,pixelScale,offsetX,offsetY,rotation;
                function clip(evt) {
                    var canvas=evt.context;
                    canvas.save();
                    var coords=highlight.getGeometry().getCoordinates();
                    var frameState = evt.frameState;
                    var pixelRatio = frameState.pixelRatio;
                    var viewState = frameState.viewState;
                    center = viewState.center;
                    var resolution = viewState.resolution;
                    rotation = viewState.rotation;
                    var size = frameState.size;
                    var size1=map.getSize();
                    offsetX = Math.round(pixelRatio * size[0] / 2);
                    offsetY = Math.round(pixelRatio * size[1] / 2);
                    pixelScale = pixelRatio / resolution;

                    canvas.beginPath();
                    if(highlight.getGeometry().getType() == 'MultiPolygon'){
                        for(var i=0;i<coords.length;i++){
                            createClip(coords[i][0], canvas);
                        }
                    }
                    else if(highlight.getGeometry().getType() == 'Polygon'){
                        createClip(coords[0], canvas);
                    }
                    canvas.clip();

                }

                function createClip(coords, canvas) {
                    for (var i = 0, cout = coords.length; i < cout; i++) {
                        var xLen = Math.round((coords[i][0] - center[0]) * pixelScale);
                        var yLen = Math.round((center[1] - coords[i][1]) * pixelScale);
                        var x = offsetX;
                        var y = offsetY;
                        if (rotation) {
                            x = xLen * Math.cos(rotation) - yLen * Math.sin(rotation) + offsetX;
                            y = xLen * Math.sin(rotation) + yLen * Math.cos(rotation) + offsetY;
                        } else {
                            x = xLen + offsetX;
                            y = yLen + offsetY;
                        }
                        if (i == 0) {
                            canvas.moveTo(x, y);
                        } else {
                            canvas.lineTo(x, y);
                        }
                    }
                    canvas.closePath();
                }
                map.on('postcompose', function(event) {
                    var ctx = event.context;
                    ctx.restore();
                });
            });
		}
	</script>
</head>
<body onLoad="init()">
<div id="map">
</div>
</body>
</html>

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Openlayers4中图片填充的实现

    lzugis
  • 唐宋文学诗人分布展示

    本文的数据是从搜韵获取而来的,地址为http://sou-yun.com/poetlife.html,为方便大家使用,将数据保存到了百度云盘,下载信息为:链接:...

    lzugis
  • OL4结合turf.js实现等值线

    本文分享一个结合turf.js实现前端等值线的生成,并对结果做了圆滑处理,并在OL4中进行展示。

    lzugis
  • Openlayers4中图片填充的实现

    lzugis
  • OL4结合turf.js实现等值线

    本文分享一个结合turf.js实现前端等值线的生成,并对结果做了圆滑处理,并在OL4中进行展示。

    lzugis
  • 唐宋文学诗人分布展示

    本文的数据是从搜韵获取而来的,地址为http://sou-yun.com/poetlife.html,为方便大家使用,将数据保存到了百度云盘,下载信息为:链接:...

    lzugis
  • OpenLayers3基础教程——OL3 介绍interaction

    本节主要讲述OL3的交互操作interaction,重点介绍draw,select以及modify。

    lzugis
  • 一个GISER 6.7的祝福

    一年一度的高考今天开始了,回想10年前,那是我第一次高考;10年后,作为一个GISER,在此给大家献上一个GISER的祝福,祝愿各位考生:考神附体,考完报考GI...

    lzugis
  • Openlayers3加载天地图

    在前文中分别讲到了在Arcgis for js、Openlayers2中去加载天地图,同时也讲到了天地图的离线加载方式。在本文,讲述在Openlayers3中实...

    lzugis
  • 一个朴素的搜索引擎实现

    今天我们要使用 Lucene 来实现一个简单的搜索引擎,我们要使用上一节爬取的果壳网语料库来构建索引,然后在索引的基础上进行关键词查询。

    老钱

扫码关注云+社区

领取腾讯云代金券