开源OpenLayers

基于openlayers6的地图卷帘控件的实现

2020-02-19  本文已影响0人  初见_JS

参考官网layer-swipe示例,通过封装成vue组件,便于后续重复调用

LayerSwipe.js中实现

import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import { getRenderPixel } from 'ol/render';
export default {
    rightLayer: null,
    map: null,
    init(mapDiv) {
        let leftURL = 'http://wprd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7'; // 高德矢量图
        let rightURL = 'http://wprd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=6';//影像路图(含路网,含注记)
        var leftLayer = new TileLayer({
            source: new XYZ({
                url: leftURL
            })
        });
        var rightLayer = new TileLayer({
            source: new XYZ({
                url: rightURL
            })
        });
        var map = new Map({
            layers: [leftLayer, rightLayer],
            target: mapDiv,
            view: new View({
                center: [0, 0],
                zoom: 2
            })
        });
        this.rightLayer = rightLayer;
        this.map = map;
    },
    mapSwipe() {
        var swipe = document.getElementById('swipe');
        var map = this.map;
        this.swipeRender(map);
        swipe.addEventListener('input', function () {
            map.render();
        }, false);
    },
    swipeRender(map) {
        this.rightLayer.on('prerender', function (event) {
            var ctx = event.context;
            var mapSize = map.getSize();
            var width = mapSize[0] * (swipe.value / 100);
            var tl = getRenderPixel(event, [width, 0]);
            var tr = getRenderPixel(event, [mapSize[0], 0]);
            var bl = getRenderPixel(event, [width, mapSize[1]]);
            var br = getRenderPixel(event, mapSize);

            ctx.save();
            ctx.beginPath();
            ctx.moveTo(tl[0], tl[1]);
            ctx.lineTo(bl[0], bl[1]);
            ctx.lineTo(br[0], br[1]);
            ctx.lineTo(tr[0], tr[1]);
            ctx.closePath();
            ctx.clip();
        });

        this.rightLayer.on('postrender', function (event) {
            var ctx = event.context;
            ctx.restore();
        });
    }

}

组件中调用

<template>
  <div style="height: 90%">
    <div id="map" class="map"></div>
    <input id="swipe" type="range" style="width: 100%" />
  </div>
</template>

<script>
import swipe from "@/views/js/LayerSwipe";
export default {
  data() {
    return {
      currentMap: null
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      swipe.init("map");
      swipe.mapSwipe();
    }
  }
};
</script>

<style>
#map {
  width: 100%;
  height: 100%;
}
</style>
上一篇下一篇

猜你喜欢

热点阅读