geotools的空间索引使用——R树和四叉树
点索引可以用网格索引kdtree
线和面的索引用strtree或者QuadTree
/**
* 空间索引之st R树
*/
public static void stRTreeTest(){
String filePath = "E:\\gis资料\\测试数据\\道路中心线.shp";
SimpleFeatureCollection sfc = fromShapeFile(filePath);
SimpleFeatureIterator iterator = sfc.features();
STRtree stRtree = new STRtree(sfc.size());
while (iterator.hasNext()){
Feature ft = iterator.next();
MultiLineString multiLineString = (MultiLineString)((SimpleFeature) ft).getDefaultGeometry();
stRtree.insert(multiLineString.getEnvelopeInternal(),ft);
}
System.out.println("str树深度:"+stRtree.depth());
stRtree.build();
System.out.println("str树深度:"+stRtree.getRoot().getLevel());
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
Geometry point = geometryFactory.createPoint(new Coordinate(120.68,30.76));
Envelope search = new Envelope(point.getCoordinate());
search.expandBy(0.001);
Date start = new Date();
List result = stRtree.query(search);
// MySizeOf.sizeOf(stRtree);
System.out.println("总数据量:"+stRtree.size()+"条");
System.out.println("查询结果:"+result.size()+"条");
System.out.println("STR树索引查找耗时:"+(new Date().getTime() - start.getTime()));
}
/**
* 空间索引之st 四叉树
* 点索引使用kdtree最好
*/
public static void QuadtreeTest(){
String filePath = "E:\\gis资料\\测试数据\\道路中心线.shp";
SimpleFeatureCollection sfc = fromShapeFile(filePath);
SimpleFeatureIterator iterator = sfc.features();
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
Geometry point = geometryFactory.createPoint(new Coordinate(120.68,30.76));
Quadtree quadtree = new Quadtree();
Date start = new Date();
while (iterator.hasNext()){
Feature ft = iterator.next();
MultiLineString multiLineString = (MultiLineString)((SimpleFeature) ft).getDefaultGeometry();
/*if(multiLineString.intersects(point)){
break;
}*/
quadtree.insert(multiLineString.getEnvelopeInternal(),ft);
}
System.out.println("无索引查找耗时:"+(new Date().getTime() - start.getTime()));
start = new Date();
Envelope search = new Envelope(point.getCoordinate());
OctagonalEnvelope searchGeom = new OctagonalEnvelope(point.getCoordinate());
searchGeom.expandBy(0.001);
search.expandBy(0.001);
List result = quadtree.query(search);
System.out.println(result.get(0).getClass());
List lastRs = new ArrayList();
for(Object ob : result){
SimpleFeature sft = (SimpleFeature)ob;
Geometry lineGeom = (Geometry)sft.getDefaultGeometry();
if(lineGeom.intersects(searchGeom.toGeometry(geometryFactory))){
lastRs.add(ob);
}
}
System.out.println("总数据量:"+quadtree.size()+"条");
System.out.println("查询结果:"+lastRs.size()+"条");
System.out.println("四叉树深度:"+quadtree.depth());
System.out.println("四叉树树索引查找耗时:"+(new Date().getTime() - start.getTime()));
}
总数据量:67749条
查询结果:8条
STR树索引查找耗时:29
查询结果:8条
四叉树深度:28
四叉树树索引查找耗时:35