地图放大镜的实现

2021/11/26 6:10:08

本文主要是介绍地图放大镜的实现,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

概述

闲来无事,就做一个花里胡哨的功能:地图放大镜,从中可以学习:1、根据坐标计算对应级别的切片;2、canvas绘图。

实现效果

实现效果

实现思路

  1. 注册mappointermove事件;
  2. 通过当前级别+放大级别,计算当前坐标所在放大级别对应的切片;
  3. 请求切片图片,并绘制到canvas上面;

实现代码

const tileSize = 256
const canvas = document.createElement('canvas')
canvas.width = tileSize
canvas.height = tileSize
const ctx = canvas.getContext('2d')
const scale = 4
canvas.classList.add('canvas')
map.getTargetElement().appendChild(canvas)
function getCoordsTile(coords) {
  let resolution = 156543.03392804097
  let resolutions = []
  for (let i = 0; i < 19; i++) {
    resolutions.push(resolution)
    resolution = resolution/ 2
  }
  const val0 = resolutions[0] * tileSize / 2
  const originX = -val0
  const originY = val0
  let zoom = Math.ceil(map.getView().getZoom()) + scale
  zoom = zoom > 18 ? 18: zoom
  const res = resolutions[zoom] * tileSize
  const x = Math.floor((coords[0] - originX) / res)
  const y = Math.floor((originY - coords[1]) / res)
  return {zoom, x, y}
}
// 地图拖动和缩放事件
map.on('pointermove', function (e) {
  vecSource.clear()
  const pixel = e.pixel
  const coords = e.coordinate
  const feature = new ol.Feature({
    geometry: new ol.geom.Point(coords)
  })
  vecSource.addFeature(feature)
  const {zoom, x, y} = getCoordsTile(coords)
  let url = options.tileUrl.split('{z}').join(zoom)
  url = url.split('{x}').join(x)
  url = url.split('{y}').join(y)
  const img = new Image()
  img.src = url
  img.onload = function () {
    ctx.beginPath()
    ctx.arc(tileSize / 2, tileSize / 2, tileSize / 2, 0, Math.PI * 2)
    ctx.clip()
    ctx.drawImage(img, 0, 0)
    canvas.style.left = pixel[0] + 'px'
    canvas.style.top = pixel[1] + 'px'
  }
})


这篇关于地图放大镜的实现的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程