概述
闲来无事,就做一个花里胡哨的功能:地图放大镜,从中可以学习:1、根据坐标计算对应级别的切片;2、canvas绘图。
实现效果
实现思路
- 注册
map
的pointermove
事件; - 通过当前级别+放大级别,计算当前坐标所在放大级别对应的切片;
- 请求切片图片,并绘制到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'
}
})