一、背景
因为国内对地理坐标有特殊的政策,所有电子地图必须对位置做偏移处理,这导致了从底层接口得到的经纬度坐标展示在地图上会有偏移。
二、前期准备
1、引入gcoord
npm install gcoord --save
import gcoord from 'gcoord'
// 或者
import { transform, WGS84, GCJ02 } from 'gcoord'
2、初始化地图参考之前文章或官方文档。
三、处理偏移
1、整体图层偏移
拿到初始化后的地图map,将新偏移过的baselayer图层重新加载至map中。
let tileLayer = new maptalks.TileLayer("baseLayer", {
urlTemplate: url,
offset: function (z) {
//实时计算wgs84和gcj02瓦片的偏移量 将GCJ02坐标转换为WGS84坐标
const center = map.getCenter();
const c = gcoord.transform(center.toArray(), gcoord.GCJ02, gcoord.WGS84);
const offset = map.coordToPoint(center, z).sub(map.coordToPoint(new maptalks.Coordinate(c), z));
return offset._round().toArray();
},
})
map.setBaseLayer(tileLayer)
2、个别点偏移
// 将GCJ02坐标转换为WGS84坐标
const point = gcoord.transform([123, 45], gcoord.GCJ02, gcoord.WGS84);