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());
你可以用你自己版本的缺失函数来扩展 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
}
function polygonCenter(poly) {
const vertices = poly.getPath();
// put all latitudes and longitudes in arrays
const longitudes = new Array(vertices.length).map((_, i) => vertices.getAt(i).lng());
const latitudes = new Array(vertices.length).map((_, i) => vertices.getAt(i).lat());
// sort the arrays low to high
latitudes.sort();
longitudes.sort();
// get the min and max of each
const lowX = latitudes[0];
const highX = latitudes[latitudes.length - 1];
const lowy = longitudes[0];
const highy = longitudes[latitudes.length - 1];
// center of the polygon is the starting point plus the midpoint
const centerX = lowX + ((highX - lowX) / 2);
const centerY = lowy + ((highy - lowy) / 2);
return (new google.maps.LatLng(centerX, centerY));
}
val bounds = LatLngBounds.Builder()
for(i in 0 until mPoints.size) {
val point = LatLng(mPoints[i].latitude, mPoints[i].longitude)
bounds.include(point)
}
mMap.moveCamera(CameraUpdateFactory.newLatLng(bounds.build().center))
// Construct the polygon.
const polygong= new google.maps.Polygon({
paths: polyCoords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: "#FF0000",
fillOpacity: 0.35,
});
var bounds = new google.maps.LatLngBounds();
polyCoords.forEach(function(coord, index)
{
bounds.extend(coord);
});
//Note: "map" object already set and initialized elsewhere but not shown in code snippet to reduce verbosity
map.setCenter(bounds.getCenter());