問題來源
在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);
}