var circle = new BMapGL.Circle(new BMapGL.Point(this.details.longitude, this.details.latitude), this
.radius, {
fillColor: "yellow",
strokeWeight: 1,
fillOpacity: 1,
strokeOpacity: 0.3
});
this.map.addOverlay(circle);
this.map.setViewport(circle.getPath())
如上,使用百度地图默认circle覆盖物,会出现如下效果
不符合预期,所以改用其他方式,代码如下:
loadCircleOverlay(center, radius, options) {
// 创建圆形覆盖物
const circleCenter = center; // 圆心坐标
const circleRadius = radius; // 半径,单位米
// const circle = new BMapGL.Circle(circleCenter, circleRadius, circleOptions);
// this.map.addOverlay(circle);
// 创建自定义覆盖物
function CustomOverlay(center, radius) {
this._center = center;
this._radius = radius;
}
CustomOverlay.prototype = new BMapGL.Overlay();
CustomOverlay.prototype.initialize = function(map) {
this._map = map;
const div = this._div = document.createElement("div");
div.style.position = "absolute";
div.style.borderRadius = "50%";
div.style.background = options.background;
div.style.border = options.border;
div.style.zIndex = options.zIndex; // 确保覆盖物在顶层显示
map.getPanes().floatPane.appendChild(div);
return div;
};
CustomOverlay.prototype.draw = function() {
const map = this._map;
const center = map.pointToOverlayPixel(this._center);
// 计算像素半径
const pointB = new BMapGL.Point(this._center.lng, this._center.lat + this._radius / 111320);
const pixelB = map.pointToOverlayPixel(pointB);
const radiusInPixels = Math.abs(pixelB.y - center.y);
this._div.style.left = center.x - radiusInPixels + "px";
this._div.style.top = center.y - radiusInPixels + "px";
this._div.style.width = radiusInPixels * 2 + "px";
this._div.style.height = radiusInPixels * 2 + "px";
};
const customOverlay = new CustomOverlay(circleCenter, circleRadius);
this.map.addOverlay(customOverlay);
// 更新覆盖物的位置和大小
const updateOverlay = () => {
customOverlay.draw();
};
// 添加事件监听器
this.map.addEventListener('zoomend', updateOverlay);
this.map.addEventListener('moveend', updateOverlay);
// 定位到圆的区域,确保圆形覆盖物完全在可视区域内
const circleBounds = this.getCircleBounds(circleCenter, circleRadius);
this.map.setViewport([circleBounds.getSouthWest(), circleBounds.getNorthEast()]);
},
// 设置圆的边界
getCircleBounds(center, radius) {
// 计算圆的边界
const dLng = radius / (111320 * Math.cos(center.lat * (Math.PI / 180)));
const dLat = radius / 110540;
const sw = new BMapGL.Point(center.lng - dLng, center.lat - dLat);
const ne = new BMapGL.Point(center.lng + dLng, center.lat + dLat);
return new BMapGL.Bounds(sw, ne);
},
使用方式:
this.loadCircleOverlay(new BMapGL.Point(this.details.longitude, this.details.latitude), this.radius, {
background: 'rgba(0,0,255,0.3)',
border: '2px solid blue',
zIndex: 10000
})
效果如下:
符合预期