Home  >  Article  >  Web Front-end  >  How to calculate polygon centroid in JavaScript

How to calculate polygon centroid in JavaScript

亚连
亚连Original
2018-06-08 16:25:212568browse

This article mainly introduces the method of calculating the centroid of polygons using JavaScript, and analyzes the relevant operating techniques of JavaScript for the mathematical calculation of the centroid of polygons in the form of examples. Friends in need can refer to it

The examples in this article describe JavaScript Implement a method for calculating the centroid of a polygon. Share it with everyone for your reference, the details are as follows:

Recently, I want to display the annotation of polygons based on Baidu Map, so I studied the calculation of the centroid of Polygon. The code is as follows:

function Area(p0,p1,p2)
{
  var area = 0.0 ;
  area = p0.lng * p1.lat + p1.lng * p2.lat + p2.lng * p0.lat - p1.lng * p0.lat - p2.lng * p1.lat - p0.lng * p2.lat;
  return area / 2 ;
}
//line 249 计算polygon的质心
function getPolygonAreaCenter(points) {
  var sum_x = 0;
  var sum_y = 0;
  var sum_area = 0;
  var p1 = points[1];
  debugger;
  for (var i = 2; i < points.length; i++) {
    p2=points[i];
    area = Area(points[0],p1,p2) ;
    sum_area += area ;
    sum_x += (points[0].lng + p1.lng + p2.lng) * area;
    sum_y += (points[0].lat + p1.lat + p2.lat) * area;
    p1 = p2 ;
  }
  var xx = sum_x / sum_area / 3;
  var yy = sum_y / sum_area / 3;
  return new BMap.Point(xx, yy);
}

The effect of annotating text As follows:

#The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to use enumeration types to implement HTML drop-down boxes in Vue

How to package static resources in Vue

js scope and pre-parsing mechanism (detailed tutorial)

The above is the detailed content of How to calculate polygon centroid in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn