最近项目用到:在不规则多边形的中心点加一个图标。(e.g: xx地区发生暴雪,暴雪区域是多边形,给多边形中心加一个暴雪的图标)java
以前的设计是,计算不规则多边形范围矩形bounds的中心点。这个比较简单,对于一些圆,矩形,凸多边形都比较适合。可是遇到凹多边形就会出现问题,好比一个月牙型的不规则多边形,bounds的中心点,就落到月牙外了。就有点难以接受了。git
通过讨论,决定将中心改成重心。ui
下面上代码,.net
计算不规则多边形的中心:设计
[java] view plain copyget
public static final double MIN_LAT = -90;
public static final double MAX_LAT = 90;
public static final double MIN_LNG = -180;
public static final double MAX_LNG = 180;it
/**List
// 经度最小值
public static double getMinLongitude(List<LatLng> mPoints) {
double minLongitude = MAX_LNG;
if (mPoints.size() > 0) {
minLongitude = mPoints.get(0).longitude;
for (LatLng latlng : mPoints) {
// 经度最小值
if (latlng.longitude < minLongitude)
minLongitude = latlng.longitude;
}
}
return minLongitude;
}map
// 经度最大值
public static double getMaxLongitude(List<LatLng> mPoints) {
double maxLongitude = MIN_LNG;
if (mPoints.size() > 0) {
maxLongitude = mPoints.get(0).longitude;
for (LatLng latlng : mPoints) {
// 经度最大值
if (latlng.longitude > maxLongitude)
maxLongitude = latlng.longitude;
}
}
return maxLongitude;
}方法
// 纬度最小值
public static double getMinLatitude(List<LatLng> mPoints) {
double minLatitude = MAX_LAT;
if (mPoints.size() > 0) {
minLatitude = mPoints.get(0).latitude;
for (LatLng latlng : mPoints) {
// 纬度最小值
if (latlng.latitude < minLatitude)
minLatitude = latlng.latitude;
}
}
return minLatitude;
}
// 纬度最大值
public static double getMaxLatitude(List<LatLng> mPoints) {
double maxLatitude = MIN_LAT;
if (mPoints.size() > 0) {
maxLatitude = mPoints.get(0).latitude;
for (LatLng latlng : mPoints) {
// 纬度最大值
if (latlng.latitude > maxLatitude)
maxLatitude = latlng.latitude;
}
}
return maxLatitude;
}
计算不规则多边形的重心:
[java] view plain copy
/**
public final double latitude;
public final double longitude;
经过这张图,就能够发现中心和重心的区别了