问题来源
在JS上很难进行全面而细致的交集运算,所以转到后台执行。同时JTS是优秀的拓扑运算开源组件,故本文使用JTS作为工具,而出于安卓考虑,使用了低版本的JTS。(jts-1.13.jar)
后台的方法
核心就是WKTReader的读取,以及各类Geometry的应用。
/**
* 获取中心点
* @param wkt 熟知文本
* @return [x,y]
* @throws ParseException
*/
public static double[] getCentroid(String wkt) throws ParseException{
WKTReader reader = new WKTReader();
double[] result = new double[2];
Geometry geom = reader.read(wkt);
Point centroid = geom.getCentroid();
if(!centroid.isEmpty() && centroid.isValid()){
result[0] = centroid.getX();
result[1] = centroid.getY();
}else{
throw new IllegalArgumentException("没有有效的中心点");
}
return result;
}
/**
* 求交集
* @param wkt 熟知文本
* @param polys 内部集
* @throws ParseException
*/
public static String getPolyWithInteraction(String wkt, String[] polys) throws ParseException{
GeometryFactory gf = new GeometryFactory();
GeometryTransformer gt = new GeometryTransformer();
WKTReader reader = new WKTReader();
Geometry geom = reader.read(wkt);
String type = geom.getGeometryType();
if("Polygon".equals(type)){
Polygon polygon = (Polygon)geom;
int num_rings = polys.length;
List<LinearRing> holes = new ArrayList<LinearRing>();
for(int i=0;i<num_rings;i++){
Polygon interaction = (Polygon)polygon.intersection(reader.read(polys[i]));
holes.add((LinearRing)gt.transform(interaction.getExteriorRing()));
}
Polygon final_geom = gf.createPolygon((LinearRing)polygon.getExteriorRing(), holes.toArray(new LinearRing[num_rings]));
return final_geom.toText();
}
return null;
}
/**
* 计算距离特定点的距离
* @param centerX 中心点 经度
* @param centerY 中心点 纬度
* @param locationX 当前经度
* @param locationY 当前纬度
* @return
*/
private static double getDistance(double[] centre,double locationX,double locationY){
double centreX = centre[0];
double centreY = centre[1];
int r = 6362790;
double x1 = centreX * Math.PI/180;
double x2 = locationX * Math.PI/180;
double y1 = centreY * Math.PI/180;
double y2 = locationY * Math.PI/180;
double dx = Math.abs(x1-x2);
/*double dy = Math.abs(y1-y2);*/
double temp = Math.cos(y1) * Math.cos(y2) * Math.cos(dx) + Math.sin( y1 ) * Math.sin(y2);
return r *Math.acos(temp);
}