How does openlayers calculate polygon offset

Idea: You can use the ol.extent.getCenter() function to get the center point of the polygon, and then calculate the angle of each vertex relative to the center point to get the offset angle of each side.

import {
    
    getCenter} from "ol/extent";
const center = getCenter(polygon.getExtent()); // 获取多边形的中心点
const coordinates = polygon.getCoordinates()[0]; // 获取多边形的坐标数组
const angles = [];
// 计算每个边的偏移角度
for (let i = 0; i < coordinates.length - 1; i++) {
    
    
  var p1 = coordinates[i];
  var p2 = coordinates[i + 1];
  var dx = p2[0] - p1[0];
  var dy = p2[1] - p1[1];
  var angle = Math.atan2(dy, dx); // 计算两点之间的角度
  angles.push(angle);
}
// 最后一个点和第一个点之间的角度
var p1 = coordinates[coordinates.length - 1];
var p2 = coordinates[0];
var dx = p2[0] - p1[0];
var dy = p2[1] - p1[1];
var angle = Math.atan2(dy, dx);
angles.push(angle);
console.log(angles); // 输出每个边的偏移角度

In the above code, we first get the center point of the polygon and the coordinate array, then we loop through each vertex and calculate each corresponding angle.
Finally, we also need to calculate the angle between the last vertex and the first vertex and add it to the array. In this way, we get the offset angle of each side.

Guess you like

Origin blog.csdn.net/qq_37489791/article/details/130238700