/**
* 获取点中心点
* @param {CoordinateType} type - 坐标类型
* @param {Projection} projection - 坐标投影转换
* @return {number[]} 中心点坐标
*/
getCenter(type: CoordinateType = CoordinateType.Latlng, projection: Projection = new WebMercator()) {
if (!this._projected) this.project(projection);
if (type === CoordinateType.Latlng) {
return [this._lng, this._lat];
} else {
return [this._x, this._y];
}
}
/**
* 获取线的中心点
* @remarks
* from Leaflet
* @param {CoordinateType} type - 坐标类型
* @param {Projection} projection - 坐标投影转换
* @return {number[]} 中心点坐标
*/
getCenter(type: CoordinateType = CoordinateType.Latlng, projection: Projection = new WebMercator()) {
if (!this._projected) this.project(projection);
let i, halfDist, segDist, dist, p1, p2, ratio,
points = this._coordinates,
len = points.length;
if (!len) { return null; }
// polyline centroid algorithm; only uses the first ring if there are multiple
for (i = 0, halfDist = 0; i < len - 1; i++) {
halfDist += Math.sqrt((points[i + 1][0] - points[i][0]) * (points[i + 1][0] - points[i][0]) + (points[i + 1][1] - points[i][1]) * (points[i + 1][1] - points[i][1])) / 2;
}
let center;
// The line is so small in the current view that all points are on the same pixel.
if (halfDist === 0) {
center = points[0];
}
for (i = 0, dist = 0; i < len - 1; i++) {
p1 = points[i];
p2 = points[i + 1];
segDist = Math.sqrt((p2[0] - p1[0]) * (p2[0] - p1[0]) + (p2[1] - p1[1]) * (p2[1] - p1[1]));
dist += segDist;
if (dist > halfDist) {
ratio = (dist - halfDist) / segDist;
center = [
p2[0] - ratio * (p2[0] - p1[0]),
p2[1] - ratio * (p2[1] - p1[1])
];
}
}
if (type === CoordinateType.Latlng) {
return projection.unproject(center);
} else {
return center;
}
}
/**
* 获取面的中心点
* @remarks
* from Leaflet
* @param {CoordinateType} type - 坐标类型
* @param {Projection} projection - 坐标投影转换
* @return {number[]} 中心点坐标
*/
getCenter(type: CoordinateType = CoordinateType.Latlng, projection: Projection = new WebMercator()) {
if (!this._projected) this.project(projection);
let i, j, p1, p2, f, area, x, y, center,
points = this._coordinates[0],
len = points.length;
if (!len) { return null; }
// polygon centroid algorithm; only uses the first ring if there are multiple
area = x = y = 0;
for (i = 0, j = len - 1; i < len; j = i++) {
p1 = points[i];
p2 = points[j];
f = p1[1] * p2[0] - p2[1] * p1[0];
x += (p1[0] + p2[0]) * f;
y += (p1[1] + p2[1]) * f;
area += f * 3;
}
if (area === 0) {
// Polygon is so small that all points are on same pixel.
center = points[0];
} else {
center = [x / area, y / area];
}
if (type === CoordinateType.Latlng) {
return projection.unproject(center);
} else {
return center;
}
}