解决百度地图缩放时图标偏移
孙泽辉 Lv5

百度地图添加了overlay后,开启缩放,在缩放时会出现坐标不正确的状况,搞了一下午,很费解。

问题复现

image

之前是缩放图标往下偏,不知道怎么搞的成往上了。

解决

自己去vue-baidu-map-plus文档上看,发现示例也有偏移问题。。

示例在zoom放到很大的时候:

image

示例在缩小的时候:

image

可以看到这个字已经快飘到山东上了。

网上看文章说是缩放的时候把滚动条也往下拖了,所以位置偏移。这个跟我情况不一致,我所有父元素都写了overflow-hidden,不存在滚动条。

或者添加zoom导航条,不再使用滚轮缩放,用导航条+和-来缩放,事实证明也不行,问题的根源还是位置计算上,跟滚动无关。

最终按照自己的理解,保证地图占满屏幕,不会出现位置计算有偏移的情况。

image

蓝色区域是百度地图的容器,为了能让他占满,把上面tabbar和title全注释了。然后问题就解决了。。。

image

想到这里已经不难了,将刚才注释的那些使用fixed固定到顶部就可以了。

为了方便,我为他们包一层.overtop

1
2
3
4
5
6
7
.overtop{
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 999999;
}

最终完美解决:

image

解决后还是不太明白,为什么一定就要按照屏幕去计算,关键计算代码应该是这里

1
2
3
4
5
6
7
8
9
10
// MapPoint.vue
const draw = ({ el, BMapGL, map }) => {
if (!props.position) return;

const { lng, lat } = props.position;
// 经纬度转换屏幕坐标
const pixel = map.pointToOverlayPixel(new BMapGL.Point(lng, lat));
el.style.left = pixel.x - 40 + "px";
el.style.top = pixel.y - 40 + "px";
};

没找到好的示例,别人都能跑我不行,先搁置吧。

2022年11月6日补充

当时没细看,第二天早上做签到打卡的时候,发现还是有点问题,有稍微的偏移(但没有之前那么严重)。任何偏移对用户的完美体验都是致命的,所以决定继续修一下。

image

在打卡范围里面,偏移显得十分明显。

还是上面的draw事件处理函数,解决方法就是给坐标添加图片对应的偏移,网上一般都是写宽或高除2,我试着不太准,还是要按照自己的情况去处理。

1
2
3
4
5
6
7
8
9
10
11
// MapPoint.vue
const draw = ({ el, BMapGL, map }) => {
if (!props.position) return;

const { lng, lat } = props.position;
// 经纬度转换屏幕坐标
const pixel = map.pointToOverlayPixel(new BMapGL.Point(lng, lat));
// icon 大小 86*86
el.style.left = pixel.x - 43 + "px";
el.style.top = pixel.y - 86 + "px";
};
image

上面是我在屏幕宽度750像素下调的偏移,你可能知道我要说什么了,在其他屏幕下还是会偏移,难道要一个个的适配吗?显然不可能。

我就想到了宽高是用vw适配的,不同屏幕下图片大小也不同,直接获取图片大小,然后和750像素下的偏移换算比例应该就可以了。

估计是讨巧吧,发现x轴偏移是图片宽度一半,y轴偏移是图片高度整体,所以:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// MapPoint.vue
// template 里去绑ref
const iconRef = ref<HTMLImageElement | null>(null);
const draw = ({ el, map }) => {
if (!props.position) return;
const { lng, lat } = props.position;
const pixel = map.pointToOverlayPixel(new BMapGL.Point(lng, lat));
let screenOffset = 86;

if (iconRef.value) {
screenOffset = iconRef.value.height;
}
el.style.left = pixel.x - screenOffset / 2 + "px";
el.style.top = pixel.y - screenOffset + "px";
};

完美解决(真的):

image
 Comments
Comment plugin failed to load
Loading comment plugin
Powered by Hexo & Theme Keep
Total words 85.5k