利用getDistance、pointToOverlayPixel计算两坐标的像素位置以及真实距离进而推算像素与实际距离比。
var pointA = r.point;
var pointB = new BMap.Point(pointA.lng + 0.0005, pointA.lat);
var realDistanceBetween2Points = map.getDistance(pointA, pointB);
var pointAPixel = map.pointToOverlayPixel(pointA);
var pointBPixel = map.pointToOverlayPixel(pointB);
var pixelDistanceBetween2Points = Math.abs(pointBPixel.x - pointAPixel.x);
console.log(`像素坐标:${JSON.stringify(pointAPixel)}和${JSON.stringify(pointBPixel)}`);
console.log(`实际距离:${realDistanceBetween2Points}`);
console.log(`1px对应的实际距离:${realDistanceBetween2Points/pixelDistanceBetween2Points}`);
var _pointA = r.point;
var _pointB = new BMap.Point(_pointA.lng , _pointA.lat + 0.0005);
var _realDistanceBetween2Points = map.getDistance(_pointA, _pointB);
var _pointAPixel = map.pointToOverlayPixel(_pointA);
var _pointBPixel = map.pointToOverlayPixel(_pointB);
var _pixelDistanceBetween2Points = Math.abs(_pointBPixel.y - _pointAPixel.y);
console.log(`像素坐标:${JSON.stringify(_pointAPixel)}和${JSON.stringify(_pointBPixel)}`);
console.log(`实际距离:${_realDistanceBetween2Points}`);
console.log(`1px对应的实际距离:${_realDistanceBetween2Points/_pixelDistanceBetween2Points}`);
在地图等级为15时打印结果如下:
这种方式偏差主要有两点,1是1像素对应x、y轴实际距离不同,2是在不同的实际距离时1px对应像素有偏差。嘛是会有这样的问题啦毕竟地球是个椭圆,而这里计算像素是在平面计算的。
直接利用百度地图提供的比例尺直接计算像素与实际距离比
new BMap.Circle(r.point,10, {fillColor:'black', strokeWeight:1, strokeColor:'red'});
这里用Circle构造函数生成一个半径10m的圆,对照比例尺内边距与实际距离比即像素与实际距离比。
贴代码
const scaleData =[
{zoom:19 ,length:20 ,Pixels:48},
{zoom:18 ,length:50 ,Pixels:61},
{zoom:17 ,length:100 ,Pixels:61},
{zoom:16 ,length:200 ,Pixels:61},
{zoom:15 ,length:500 ,Pixels:78},
{zoom:14 ,length:1000 ,Pixels:78},
{zoom:13 ,length:2000 ,Pixels:78},
{zoom:12 ,length:5000 ,Pixels:99},
{zoom:11 ,length:10000 ,Pixels:99},
{zoom:10 ,length:20000 ,Pixels:99},
{zoom:9 ,length:25000 ,Pixels:59},
{zoom:8 ,length:50000 ,Pixels:59},
{zoom:7 ,length:100000 ,Pixels:59},
{zoom:6 ,length:200000 ,Pixels:59},
{zoom:5 ,length:500000 ,Pixels:76},
{zoom:4 ,length:1000000 ,Pixels:76},
{zoom:3 ,length:2000000 ,Pixels:75}];
/**
* @param distance 实际距离
* @returns 像素距离
*/
function RealDistanceTranPixels(distance) {
let zoom = map.getZoom();
let pixDistance;
for (let i=0;i