Dan*_*llo 194
马修的答案是一个很好的解决方案.但是,在使用Google Maps API v3时,您可能希望LatLngBounds通过该extend()方法将多边形的每个点传递给对象,然后最终getCenter()在LatLngBounds对象上调用该方法.请考虑以下示例:
var bounds = new google.maps.LatLngBounds();
var i;
// The Bermuda Triangle
var polygonCoords = [
new google.maps.LatLng(25.774252, -80.190262),
new google.maps.LatLng(18.466465, -66.118292),
new google.maps.LatLng(32.321384, -64.757370),
new google.maps.LatLng(25.774252, -80.190262)
];
for (i = 0; i < polygonCoords.length; i++) {
bounds.extend(polygonCoords[i]);
}
// The Center of the Bermuda Triangle - (25.3939245, -72.473816)
console.log(bounds.getCenter());
Run Code Online (Sandbox Code Playgroud)
Mat*_*ley 63
算法:
遍历多边形中的所有点.找到所有要点;
x1,最低x坐标y1,最低y坐标x2,最高x坐标y2,最高y坐标你现在有了边界矩形,可以使用以下方法计算出中心:
center.x = x1 + ((x2 - x1) / 2);
center.y = y1 + ((y2 - y1) / 2);
Run Code Online (Sandbox Code Playgroud)
小智 47
您可以使用自己的缺失函数版本扩展Polygon类,我们将其称为my_getBounds():
google.maps.Polygon.prototype.my_getBounds=function(){
var bounds = new google.maps.LatLngBounds()
this.getPath().forEach(function(element,index){bounds.extend(element)})
return bounds
}
Run Code Online (Sandbox Code Playgroud)
而不是在像这样的代码中使用它:
myPolygon.my_getBounds().getCenter()
Run Code Online (Sandbox Code Playgroud)
......等等,它应该等同于v2的行为
这是我写的自定义函数.随意使用它.
function polygonCenter(poly) {
var latitudes = [];
var longitudes = [];
var vertices = poly.getPath();
// put all latitudes and longitudes in arrays
for (var i = 0; i < vertices.length; i++) {
longitudes.push(vertices.getAt(i).lng());
latitudes.push(vertices.getAt(i).lat());
}
// sort the arrays low to high
latitudes.sort();
longitudes.sort();
// get the min and max of each
var lowX = latitudes[0];
var highX = latitudes[latitudes.length - 1];
var lowy = longitudes[0];
var highy = longitudes[latitudes.length - 1];
// center of the polygon is the starting point plus the midpoint
var centerX = lowX + ((highX - lowX) / 2);
var centerY = lowy + ((highy - lowy) / 2);
return (new google.maps.LatLng(centerX, centerY));
}
Run Code Online (Sandbox Code Playgroud)
对于在 dart/flutter 中寻找答案的人,您可以使用以下代码实现相同的目标。
calculateCenter(List<LatLng> points) {
var longitudes = points.map((i) => i.longitude).toList();
var latitudes = points.map((i) => i.latitude).toList();
latitudes.sort();
longitudes.sort();
var lowX = latitudes.first;
var highX = latitudes.last;
var lowy = longitudes.first;
var highy = longitudes.last;
var centerX = lowX + ((highX - lowX) / 2);
var centerY = lowy + ((highy - lowy) / 2);
return LatLng(centerX, centerY);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
80697 次 |
| 最近记录: |