百度地图经纬度和像素坐标互转
1.经纬度转像素坐标
// 投影实例
const projection = map.getMapType().getProjection()
// 地图div宽高
const box = map.getSize()
const zoom = window.Math.pow(2, 18 - map.getZoom())
// 中心坐标 转 平面坐标
const center = projection.lngLatToPoint(map.getCenter())
// 测试坐标 转 平面坐标
// 这里根据自己的需求,设置point坐标
const point = projection.lngLatToPoint({ lng: 118.816832, lat: 31.981216 })
// 像素坐标
const x = Math.round((point.x - center.x) / zoom + box.width / 2)
const y = Math.round((center.y - point.y) / zoom + box.height / 2)
// 测试下 与pointToPixel转换是相同的
const pixel = map.pointToPixel({ lng: 118.816832, lat: 31.981216 })
console.log(pixel, x, y)
2.像素坐标转经纬度坐标
//投影实例
var projection = map.getMapType().getProjection();
// 地图div宽高
var box = map.getSize()
var zoom = window.Math.pow(2, 18 - map.getZoom());
// 中心坐标 转 平面坐标
var center = projection.lngLatToPoint(map.getCenter());
//元素左上角位置
var left = 100;
var top = 100;
var x = (left - box.width / 2) * zoom + center.x;
var y = center.y - (top - box.height / 2) * zoom;
var NW = map.getMapType().getProjection().pointToLngLat({
x: x,
y: y
});
//坐标点
var point = new BMap.Point(NW.lng, NW.lat);
//创建图像标注
map.addOverlay(new BMap.Marker(point));
转载于:https://my.oschina.net/jszhang/blog/3098870