画圆:new BMap.Circle(圆心, 半径米数, 样式);画矩形:new BMap.Rectangle(new BMap.Bounds(西南角, 东北角), 样式),然后都用 map.addOverlay() 加到地图上。样式和多边形相同(strokeColor、strokeWeight、fillColor、fillOpacity、strokeStyle)。设置 enableEditing: true 后,用户可以拖动手柄改变圆的半径和矩形的大小。常用来表示"周边 1 公里""配送范围""框选区域"。
画圆
js
const center = new BMap.Point(116.399, 39.925);
const circle = new BMap.Circle(center, 1500, { // 半径 1500 米
strokeWeight: 2,
strokeOpacity: 0.5,
});
map.addOverlay(circle);
map.setViewport([circle]); // 视野适配整个圆
在线示例:圆形
不传样式时使用 4.0 的默认蓝色样式。修改:circle.setCenter(point)、circle.setRadius(米);读取:getCenter()、getRadius()、getBounds()。
画矩形
js
const bounds = new BMap.Bounds(
new BMap.Point(116.38, 39.90), // 西南角
new BMap.Point(116.42, 39.93), // 东北角
);
const rectangle = new BMap.Rectangle(bounds, {
strokeColor: '#0066ff',
strokeWeight: 2,
strokeOpacity: 0.8,
strokeStyle: 'solid',
fillColor: '#0066ff',
fillOpacity: 0.3,
});
map.addOverlay(rectangle);
map.setViewport([rectangle]);
在线示例:矩形
可编辑
js
const circle = new BMap.Circle(new BMap.Point(116.404, 39.915), 1000, {
enableEditing: true,
strokeWeight: 2,
});
map.addOverlay(circle);
circle.enableEditing();
circle.disableEditing();
编辑状态下圆心和边上各有一个手柄,拖圆心移动、拖边上的手柄改半径:
判断点在不在圆内
圆内判断可以直接算距离:
js
const inCircle = map.getDistance(point, circle.getCenter()) <= circle.getRadius();
矩形用 Bounds 自带的方法:
js
bounds.containsPoint(point); // true / false
常见问题
圆在地图上看起来是椭圆?
不会。Circle 的半径按地面米数计算,在 Web 墨卡托投影下始终显示为正圆。如果看到椭圆,通常是地图容器被 CSS 拉伸了(宽高被 transform: scale 之类改变)。
圆的半径单位是什么?
米。
矩形能旋转吗?
Rectangle 始终是正南正北的。需要斜的矩形,用四个顶点画 Polygon。
和旧写法的区别
旧教程里画矩形,多数是根据两个角点手动算出四个顶点再画 Polygon,判断圆内点则引入 GeoUtils 插件。4.0 有现成的 BMap.Rectangle,直接传 Bounds,圆和矩形都支持编辑;简单的范围判断用 getDistance 和 Bounds.containsPoint 就够了。Circle 的写法和旧版一致,默认样式更新为新的蓝色主题。