Openlayers笔记之实现卷帘查看功能

Web GIS 的开发中,总是会遇到很多新奇的需求,比如卷帘查看功能。
卷帘查看是为了方便比较不同时间、不同类型的两张地图在同一地点的差异性,通过卷帘操作能够快速对比出两张地图的差异性。

1.实现思路

Openlayers API文档中提供了控制地图范围的接口(Extent)。通过加载两张地图,移动前端绘制的卷帘轴,实时获取卷帘轴当前的屏幕坐标(x, y),并实时控制上面层级地图的显示范围,即可实现该功能。

2.具体实现

首先创建图层,加载两张在线地图:

/*
* 初始化地图
*/
function initMap() {
  window.olMap = new window.ol.Map({
    target: 'map',
    layers: [
      new window.ol.layer.Tile({
        // 加载 在线地图1
        source: new window.ol.source.TileArcGISRest({
          url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',
          wrapX: true,
          tileSize: [256, 256]
        }),
        zIndex: 1
      }),
      new window.ol.layer.Tile({
        // 加载 在线地图2
        source: new window.ol.source.XYZ({
          url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=6',
          wrapX: true,
          tileSize: [256, 256]
        }),
        zIndex: 1
      })
    ],
    view: new window.ol.View({
      center: window.ol.proj.fromLonLat([120.16, 32.71]),
      zoom: 13,
      enableRotation: true
    }),

    pixelRatio: typeof window.devicePixelRatio !== 'undefined' ? window.devicePixelRatio : 1
  });

  // 初始化设置 两张地图 各占一半
  setTimeout(() => {
    updateMapExtent({
      x: window.document.documentElement.clientWidth / 2,
      y: 0
    });
  })
}

其次根据 openlayers 提供的接口,编写更新地图范围的二次开发接口:

/*
* 调用方法更新 地图 范围
*/
function updateMapExtent (windowPostion) {
  // 将屏幕坐标 转换为 地图坐标
  let pos = window.olMap.getCoordinateFromPixel([windowPostion.x, windowPostion.y])

  // 修改第二个地图的范围
  window.olMap.getLayers().getArray()[1].setExtent([0, 0, pos[0], pos[1]])
}

最后,控制卷帘轴的移动,实时获取卷帘轴的屏幕坐标,并调用 updateMapExtent 方法实现功能!

/*
* 绑定事件
*/
function bindMoveEvent () {
  window.document.addEventListener('mousemove', function (e) {
    document.getElementById('line').style.left = (e.x - 4) + 'px';
    updateMapExtent({
      x: e.x,
      y: 0
    });
  })
}

3.最终效果

卷帘查看

4.总结

以上是 Openlayers 实现卷帘查看的方法,Cesium 也可以采用同样的思路实现。

注:示例代码可参见 OL_RollerView


created by @SpiderWang
转载请注明作者及链接

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值