ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Openlayers笔记之图片偏移的完整解决方案

2021-12-19 16:02:35  阅读:396  来源: 互联网

标签:ol 解决方案 window scale 偏移 new Openlayers 图片


本文介绍 Openlayers 如何实现图片偏移标注的功能,同时提供在图片缩放比例变化时纠正偏移的解决方法。

1.创建矢量图层

// 创建矢量源
window.vectorSource = new window.ol.source.Vector({
  features: []
})
// 创建并添加矢量标注图层
window.olMap.addLayer(new window.ol.layer.Vector({
  source: window.vectorSource,
  zIndex: 2
}))

2.创建图片标绘方法

利用 API 提供的 anchor 属性实现图片偏移标注:

/*
* 创建图片标绘
*/
function createIcon (coords) {
  let feature = new window.ol.Feature(
    new window.ol.geom.Point(coords)
  )

  feature.setStyle(new window.ol.style.Style({
    image: new window.ol.style.Icon({
      src: 'res/logo.png',  // 图标的URL
      anchor: [20, 50], // 偏移的 x 与 y 方向值,注意此值与 Cesium 等GIS库偏向方向正好相反
      anchorXUnits: 'pixels',
      anchorYUnits: 'pixels'
    })
  }))

  return feature
}

3.点击地图完成图片标绘

window.olMap.on('click', (e) => {
  // 鼠标单击点的坐标
  let coords = e.coordinate
  
  // 创建图标
  window.vectorSource.addFeature(createIcon(coords));
})

4.存在问题

上述方法能够完成基本的图片偏移,但经过与 CesiumGIS 库的图片偏移 API 进行对比发现 Openlayers 存在以下几个问题:

  • 锚点偏移方向与其他 GIS 库正好相反,且偏移量存在问题
  • 图片缩放比例变化时偏移量不会自适应变化,导致偏移量存在问题(不随比例值变化而变化)

5.解决方案

针对第一个问题,需要将 anchor 里的 xy 方向偏移值设为负值,即可与其他库保持偏移方向一致:

feature.setStyle(new window.ol.style.Style({
  image: new window.ol.style.Icon({
    src: 'res/logo.png',  // 图标的URL
    anchor: [-anchorX, -anchorY],
    anchorXUnits: 'pixels',
    anchorYUnits: 'pixels'
  })
}))

针对第二个问题,需要获取图片原始大小后,同步根据缩放比例值变化进行偏移量的纠偏,具体实现如下:

// 通过 `Image` 获取图片原始大小
let img = new Image()
img.src = 'res/logo.png'

img.onload = () => {
  // 获取图片实际大小
  let imgWidth = img.width
  let imgHeight = img.height

  // 假设图片缩放比例为 scale,x 偏移为 anchorX; y 偏移为 anchorY
  // 1、首先对偏移量进行反向兼容,即 -anchorX  -anchorY
  // 2、其次进行中心位置 和 缩放比例纠偏 (imgWidth / 2.0) * scale - anchorX
  // 3、最后再根据缩放比例纠回偏移量
  let anchorX = ((imgWidth / 2.0) * scale - anchorX) / scale
  let anchorY = ((imgHeight / 2.0) * scale - anchorY) / scale

  // 完成图片偏移标注
  feature.setStyle(new window.ol.style.Style({
    image: new window.ol.style.Icon({
      src: 'res/logo.png',  // 图标的URL
      scale: scale,
      anchor: [anchorX, anchorY],
      anchorXUnits: 'pixels',
      anchorYUnits: 'pixels'
    })
  }))
}

6.总结

openlayers 库与其他 GIS 库在图片偏移上的锚定位置不一致,需要计算其原始图片中心位置,同时根据缩放比例进行纠偏,才能达到与其他库一致的效果。


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

标签:ol,解决方案,window,scale,偏移,new,Openlayers,图片
来源: https://blog.csdn.net/Spider_wang/article/details/122025041

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有