使用leaflet,输入一个起点、一个终点,画出扇形,可以自由设置扇形角度。
// 勾画扇形start
let start = [40.065778, 116.307747];
let end = [40.065, 116.307];
let sector;// 扇形对象
drawSector(start, end);
// [入口]给定起止点,画扇形
function drawSector(start, end) {
if (sector) map.removeLayer(sector);
let B = bearing(start, end);
var points = getPoints(start, 0.0003, B, 50);
points[points.length] = points[0];
sector = L.polygon(points).addTo(map);
}
/**
* @param center 中心点 数组
* @param radius 半径
* @param bearing 两点间角度
* @param //startAngle 起始角度
* @param //endAngle 终止角度
* @param pointNum 圆弧上点的个数
*/
function getPoints(center, radius, bearing, pointNum) {
var startAngle = bearing - 20,//调整以设置扇形角度
endAngle = bearing + 20;//调整以设置扇形角度
var sin;
var cos;
var x;
var y;
var angle;
var points = new Array();
points.push(center);
for (var i = 0; i <= pointNum; i++) {
angle = startAngle + (endAngle - startAngle) * i / pointNum;
sin = Math.sin(angle * Math.PI / 180);
cos = Math.cos(angle * Math.PI / 180);
y = center[0] + radius * cos;
x = center[1] + radius * sin;
points[i] = [y, x];
}
var point = points;
point.push(center);
return point;
}
/*
* 计算两点对于正北方向的朝向角度 [0,360]
* @param {*} start format:[40.065778, 116.307747] [40.065, 116.307]
* @param {*} end
*/
function bearing(start, end) {
let rad = Math.PI / 180,
lat1 = start[0] * rad,
lat2 = end[0] * rad,
lon1 = start[1] * rad,
lon2 = end[1] * rad;
const a = Math.sin(lon2 - lon1) * Math.cos(lat2);
const b = Math.cos(lat1) * Math.sin(lat2) -
Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1);
return radiansToDegrees(Math.atan2(a, b));
}
/*
* 弧度转换为角度
*/
function radiansToDegrees(radians) {
const degrees = radians % (2 * Math.PI);
return degrees * 180 / Math.PI < 0 ? 360 + degrees * 180 / Math.PI : degrees * 180 / Math.PI;
}
// 勾画扇形end
参考大佬: