`
longgangbai
  • 浏览: 7330411 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论
阅读更多

前段时间的一个项目 本来用ae完成了种种的 查询,空间分析等等功能的代码,但是不幸的是 这是一个web项目,无奈 ae各种错误,显然ae放在server端是不好使的 无奈 一咬牙一跺脚 全部换 换成geotools  看文档 看api 从零 开始算是把 原来AE实现的东西 统统改了过来 用起来 反而觉得既稳定 效率还不错哈!

以下是部分功能总结:

1、连接数据库 这里使用的postgis 链接代码如下:

 

private static void conn(String dbtype, String host, String port,
			String database, String userName, String password) {
		Map<String, Object> params = new HashMap<String, Object>();
		// params.put(PostgisNGDataStoreFactory.DBTYPE.key, "postgis");    // 两种代码方式
		// params.put(PostgisNGDataStoreFactory.HOST.key, "localhost");
		// params.put(PostgisNGDataStoreFactory.PORT.key, new Integer(5432));
		// params.put(PostgisNGDataStoreFactory.DATABASE.key, "postgis");
		// params.put(PostgisNGDataStoreFactory.SCHEMA.key, "public");
		// params.put(PostgisNGDataStoreFactory.USER.key, "postgres");
		// params.put(PostgisNGDataStoreFactory.PASSWD.key, "root");
		params.put(PostgisNGDataStoreFactory.DBTYPE.key, dbtype);
		params.put(PostgisNGDataStoreFactory.HOST.key, host);
		params.put(PostgisNGDataStoreFactory.PORT.key, new Integer(port));
		params.put(PostgisNGDataStoreFactory.DATABASE.key, database);
		params.put(PostgisNGDataStoreFactory.SCHEMA.key, "public");
		params.put(PostgisNGDataStoreFactory.USER.key, userName);
		params.put(PostgisNGDataStoreFactory.PASSWD.key, password);
		try {
			pgDatastore = DataStoreFinder.getDataStore(params);
			if (pgDatastore != null) {
				System.out.println("系统连接到位于:" + host + "的空间数据库" + database
						+ "成功!");
			} else {
				System.out.println("系统连接到位于:" + host + "的空间数据库" + database
						+ "失败!请检查相关参数");
			}
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("系统连接到位于:" + host + "的空间数据库" + database
					+ "失败!请检查相关参数");
		}

	}
调用方法为:conn("postgis", "localhost", 5432, "postgis", "postgres", "root");

2、图层的操作

 

2.1 查询
public static ArrayList<SimpleFeature> queryMethod(String filterStr,
			String layerName) {
		//pgDatastore为上文连接数据库获取相当于AE中的workspace
		//SimpleFeatureSource相当于AE中的featureClass
		SimpleFeatureSource featureSource =pgDatastore.getFeatureSource(layerName); 
		ArrayList<SimpleFeature> featureList = new ArrayList<SimpleFeature>();
		if(featureSource==null)
			return featureList;
		try {
			Filter filter;
			filter = CQL.toFilter(filterStr); // filterStr形式 如  name='武汉大学' or code like 'tt123%'
			SimpleFeatureCollection result = featureSource.getFeatures(filter);

			FeatureIterator<SimpleFeature> itertor = result.features();
			while (itertor.hasNext()) {
				SimpleFeature feature = itertor.next();
				featureList.add(feature);
			}
			itertor.close();
			return featureList;
		} catch (CQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
2.2 要素操作  对上面4.1中的 SimpleFeature操作
//获取feature的geometry
Geometry geo=(Geometry) feature.getDefaultGeometry();
//获取geometry中的坐标 这里用string的方式保存
int geoUnm = geo.getNumGeometries();  // 一个geometry可能含有n个geometry
for (int i = 0; i < geoUnm; i++) {
	Geometry singleGeo = geo.getGeometryN(i); //获取其中每一个geometry
	int pointCount = singleGeo.getNumPoints();
	Coordinate[] coords = singleGeo.getCoordinates();
	for (int j = 0; j < pointCount; j++) {
		if (j == pointCount - 1)
			sBuilder.append(coords[j].x + "," + coords[j].y);
		else {
			sBuilder.append(coords[j].x + "," + coords[j].y
									+ ";");
		}
	}
	if (i != geoUnm - 1) {
		sBuilder.append("|");
	}
} 
//获取feature中的属性
feature.getAttribute(arg0);
2.3 拓扑查询
public static Filter getGeoFilter(FilterFactory2 ff,                //构建拓扑查询的filter
			String geometryAttributeName, Geometry refGeo,
			SpatialReltionType.TopoRelTypeEnum relType) {   //这个SpatialReltionType是我自己定义的。。。

		switch (relType) {
		case intersect:
			return ff.intersects(ff.property(geometryAttributeName), ff
					.literal(refGeo));
		case contains:
			return ff.contains(ff.property(geometryAttributeName), ff
					.literal(refGeo));
		case within:
			return ff.within(ff.property(geometryAttributeName), ff
					.literal(refGeo));
		case cross:
			return ff.crosses(ff.property(geometryAttributeName), ff
					.literal(refGeo));
		case overlaps:
			return ff.overlaps(ff.property(geometryAttributeName), ff
					.literal(refGeo));
		case touches:
			return ff.touches(ff.property(geometryAttributeName), ff
					.literal(refGeo));
		case equals:
			return ff.equals(ff.property(geometryAttributeName), ff
					.literal(refGeo));
		case disjoint:
			return ff.disjoint(ff.property(geometryAttributeName), ff
					.literal(refGeo));
		default:
			return null;
		}
	}
// 普通的拓扑查询
public static ArrayList<Geometry> topoQueryMethod(Geometry refGeo,
			String layerName, SpatialReltionType.TopoRelTypeEnum relType) {
		ArrayList<SimpleFeature> featurelist=new ArrayList<SimpleFeature>();
		FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(null);
		SimpleFeatureSource featureSource=pgDatastore.getFeatureSource(layerName); 
	
		SimpleFeatureType schema = featureSource.getSchema();
		String geometryAttributeName = schema.getGeometryDescriptor().getLocalName();
		Filter filter1= getGeoFilter(ff,geometryAttributeName, refGeo, relType);	//上面的方法
		SimpleFeatureCollection result=null;
		try {
			result = featureSource.getFeatures(filter1);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        if(result==null)
        	return null;
		FeatureIterator<SimpleFeature> itertor = result.features();
		while (itertor.hasNext()) {
			SimpleFeature feature = itertor.next();
			featurelist.add(feature);
		}
		//这个方法是将feature转为geometry 自己定义的
		return SpatialUtil.ConverToGeoList(featurelist);  
	}
//联合属性的拓扑查询
public static ArrayList<Geometry> topoQueryMethod(Geometry refGeo,
			String queryName, String layerName,
			SpatialReltionType.TopoRelTypeEnum relType) {
		FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(null);
		ArrayList<SimpleFeature> featurelist=new ArrayList<SimpleFeature>();
		SimpleFeatureSource featureSource=pgDatastore.getFeatureSource(layerName); 
	
		SimpleFeatureType schema = featureSource.getSchema();
		String geometryAttributeName = schema.getGeometryDescriptor().getLocalName();
		Filter filter1= SpatialUtil.getGeoFilter(ff,geometryAttributeName, refGeo, relType);	
		Filter filter2=null;
		try {
		    filter2=CQL.toFilter("StandName = '"+queryName+"'");
		} catch (CQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		List<Filter> match = new ArrayList<Filter>();
		match.add(filter1);
		match.add(filter2);
		Filter filter = ff.and(match);

		SimpleFeatureCollection result=null;
		try {
			result = featureSource.getFeatures(filter);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        if(result==null)
        	return null;
		FeatureIterator<SimpleFeature> itertor = result.features();
		while (itertor.hasNext()) {
			SimpleFeature feature = itertor.next();
			featurelist.add(feature);
		}
		return SpatialUtil.ConverToGeoList(featurelist);
		
	}

3,编辑图层 

3.1 添加要素
    //添加一个feature到图层中 在添加前要确定构造featureType
	public static SimpleFeatureType createFeatureType(String typeName,Class type) {
		SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
		builder.setName(typeName);
		builder.setCRS(DefaultGeographicCRS.WGS84); // <- Coordinate reference
													// system
		builder.add("the_geom", type);  //这个为地理属性字段 postgis中为 the——geom

		builder.add("StandName", String.class); // 这是其他属性字段 自己定义的....							
		// build the type
		final SimpleFeatureType TYPE = builder.buildFeatureType();

		return TYPE;
	}
	
	//添加到图层的图层名,添加的要素空间属性和要素的某属性名
	public static boolean addFeature(String layerName,Geometry geo,String featureName){ 
		String type=geo.getGeometryType();
		Class TypeClass=null;
		if(type.toLowerCase().equals("point")){
			TypeClass=Point.class;
		}else if(type.toLowerCase().equals("polygon")){
			TypeClass=Polygon.class;
		}else if(type.toLowerCase().equals("polyline")){
			TypeClass=Polyline.class;
		}else if(type.toLowerCase().equals("multipolygon")){
		    TypeClass=MultiPolygon.class;
	    }
		SimpleFeatureType featureType=createFeatureType(layerName,TypeClass);
		 SimpleFeatureCollection collection = FeatureCollections.newCollection();

		SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType);
		 /* Longitude (= x coord) first ! */
		GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
     
        featureBuilder.add(geo);
        featureBuilder.add(featureName);
       
        SimpleFeature feature = featureBuilder.buildFeature(null);
        collection.add(feature);

        FeatureSource featureSource=pgDatastore.getFeatureSource(layerName); 
        if (featureSource instanceof SimpleFeatureStore) {
            SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
            Transaction transaction = new DefaultTransaction("create");
            featureStore.setTransaction(transaction);
            try {
                featureStore.addFeatures(collection);
                transaction.commit();
                return true;

            } catch (Exception problem) {
                problem.printStackTrace();
                try {
					transaction.rollback();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

            } finally {
                try {
					transaction.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
         
        } else {
            System.out.println(layerName + " does not support read/write access");      
        }
		return false;
	}
    3.2 修改要素
	// 修改feacode为XX的要素的名字为featureName 地理方位为geo  (feacode StandName为你的属性字段自定义)
	 public static boolean modifyFeature(String layerName,Geometry geo,String featureName,String FeaCode){
		  FeatureSource featureSource=pgDatastore.getFeatureSource(layerName); 
	        if (featureSource instanceof SimpleFeatureStore) {
	            SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
	            Transaction transaction = new DefaultTransaction("create");
	            featureStore.setTransaction(transaction);
	            try {
	            	String filterStr="FeaCode= '"+FeaCode+"'";
	            	String[] names=new String[2];
	            	names[0]="StandName";
	            	names[1]="the_geom";
	            	Object[] values=new Object[2];
	            	values[0]=featureName;
	            	values[1]=geo;
	            	featureStore.modifyFeatures(names, values, CQL.toFilter(filterStr));
	            
	               
	                transaction.commit();
                    return true;
	            } catch (Exception problem) {
	                problem.printStackTrace();
	                try {
						transaction.rollback();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

	            } finally {
	                try {
						transaction.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }
	         
	        } else {
	            System.out.println(layerName + " does not support read/write access");      
	        }
			return false;
	}

4 、Geometry 与 JTS

geotools 构建 geometry方法:这里转载一个别人写的比较好的 

4.1构建点
public Point createPoint(){  
        Coordinate coord = new Coordinate(109.013388, 32.715519);  
        Point point = geometryFactory.createPoint( coord );  
        return point;  
    } 
public Point createPointByWKT() throws ParseException{  
        WKTReader reader = new WKTReader( geometryFactory );  
        Point point = (Point) reader.read("POINT (109.013388 32.715519)");  
        return point;  
    } 
public MultiPoint createMulPointByWKT()throws ParseException{  
        WKTReader reader = new WKTReader( geometryFactory );  
        MultiPoint mpoint = (MultiPoint) reader.read("MULTIPOINT(109.013388 32.715519,119.32488 31.435678)");  
        return mpoint;  
    } 
4.2 构建线
public LineString createLine(){  
        Coordinate[] coords  = new Coordinate[] {new Coordinate(2, 2), new Coordinate(2, 2)};  
        LineString line = geometryFactory.createLineString(coords);  
        return line;  
    }  
 public LineString createLineByWKT() throws ParseException{  
        WKTReader reader = new WKTReader( geometryFactory );  
        LineString line = (LineString) reader.read("LINESTRING(0 0, 2 0)");  
        return line;  
    }  
public MultiLineString createMLine(){  
        Coordinate[] coords1  = new Coordinate[] {new Coordinate(2, 2), new Coordinate(2, 2)};  
        LineString line1 = geometryFactory.createLineString(coords1);  
        Coordinate[] coords2  = new Coordinate[] {new Coordinate(2, 2), new Coordinate(2, 2)};  
        LineString line2 = geometryFactory.createLineString(coords2);  
        LineString[] lineStrings = new LineString[2];  
        lineStrings[0]= line1;  
        lineStrings[1] = line2;  
        MultiLineString ms = geometryFactory.createMultiLineString(lineStrings);  
        return ms;  
    }  
public MultiLineString createMLineByWKT()throws ParseException{  
        WKTReader reader = new WKTReader( geometryFactory );  
        MultiLineString line = (MultiLineString) reader.read("MULTILINESTRING((0 0, 2 0),(1 1,2 2))");  
        return line;  
    } 
4.3 构建多边形
public Polygon createPolygonByWKT() throws ParseException{  
        WKTReader reader = new WKTReader( geometryFactory );  
        Polygon polygon = (Polygon) reader.read("POLYGON((20 10, 30 0, 40 10, 30 20, 20 10))");  
        return polygon;  
    }  
public MultiPolygon createMulPolygonByWKT() throws ParseException{  
        WKTReader reader = new WKTReader( geometryFactory );  
        MultiPolygon mpolygon = (MultiPolygon) reader.read("MULTIPOLYGON(((40 10, 30 0, 40 10, 30 20, 40 10),(30 10, 30 0, 40 10, 30 20, 30 10)))");  
        return mpolygon;  
    }  
4.4 构建geo集合
public GeometryCollection createGeoCollect() throws ParseException{  
        LineString line = createLine();  
        Polygon poly =  createPolygonByWKT();  
        Geometry g1 = geometryFactory.createGeometry(line);  
        Geometry g2 = geometryFactory.createGeometry(poly);  
        Geometry[] garray = new Geometry[]{g1,g2};  
        GeometryCollection gc = geometryFactory.createGeometryCollection(garray);  
        return gc;  
    } 
4.5 构建圆
public Polygon createCircle(double x, double y, final double RADIUS){  
        final int SIDES = 32;//圆上面的点个数  
        Coordinate coords[] = new Coordinate[SIDES+1];  
        for( int i = 0; i < SIDES; i++){  
            double angle = ((double) i / (double) SIDES) * Math.PI * 2.0;  
            double dx = Math.cos( angle ) * RADIUS;  
            double dy = Math.sin( angle ) * RADIUS;  
            coords[i] = new Coordinate( (double) x + dx, (double) y + dy );  
        }  
        coords[SIDES] = coords[0];  
        LinearRing ring = geometryFactory.createLinearRing( coords );  
        Polygon polygon = geometryFactory.createPolygon( ring, null );  
        return polygon;  
    }  

 

postgis 删除表  SELECT DropGeometryTable ('my_schema','my_spatial_table');

如: SELECT DropGeometryTable ('public','river');

 

分享到:
评论

相关推荐

    android GIS ---GEOtools Googlemap ucmap 开发总结

    ### Android GIS 开发总结——GEOtools、Google Maps API、UCMap #### 一、引言 随着移动设备性能的提升和技术的发展,地理信息系统(GIS)在移动平台上的应用变得越来越广泛。Android作为全球最流行的移动操作系统...

    Geotools Java API 开发gis的参考资料

    org.geotools org.geotools.arcsde org.geotools.arcsde.data org.geotools.arcsde.data.versioning org.geotools.arcsde.data.view org.geotools.arcsde.filter org.geotools.arcsde.gce org.geotools....

    geotools学习指南

    GeoTools学习指南 GeoTools是一款功能强大的开源GIS(Geographic Information System)工具包,提供了丰富的API和插件,帮助开发者快速构建GIS应用程序。在本指南中,我们将详细介绍GeoTools的基本概念、库函数、...

    geotools汉语版资料

    《GeoTools汉语版资料》是一份详实的资源集合,主要针对使用GeoTools进行地理信息系统(GIS)开发的用户。GeoTools是一个开放源代码的Java库,它实现了OGC(Open Geospatial Consortium)标准,提供了对地理空间数据...

    geotools中文资料,我学习时候,整理的资料,

    - **MyGeoTools.doc**:这可能是一份个人整理的GeoTools学习笔记,包含了使用GeoTools开发GIS应用的关键概念和代码示例。 - **MyGeoTools.mht**:可能是另一种格式的学习资料,MHT是单个文件的Web档案,可能包含...

    Geotools API 手册

    **Geotools API 手册**是一份详细的技术文档,主要针对使用Geotools库进行地理信息系统(GIS)开发的程序员。Geotools是开源Java库,它提供了一系列的工具和接口,使得开发者能够轻松地在Java应用程序中处理、分析和...

    geotools.rar

    总结来说,Java的Geotools库是一个强大的GIS开发工具,它的坐标转换功能使得开发者能够处理各种地理坐标系,而全面的数据访问和处理能力则支持了复杂的GIS应用开发。无论是从数据的读取、处理到可视化,Geotools都能...

    geotools18.1依赖jar包

    同时,GeoTools提供了丰富的API文档和示例代码,帮助开发者快速理解和使用这个库。 总的来说,GeoTools18.1是Java开发GIS应用的重要资源,无论你是构建地图服务、进行空间分析还是开发与地理空间数据相关的应用,它...

    geotools所需jar包合集

    6. **API设计**:GeoTools的API设计遵循了Java的设计模式,易于理解和使用,同时提供了丰富的示例代码和文档,帮助开发者快速上手。 在实际项目中,开发者可以根据需求选择导入压缩包中的特定jar包,比如如果只需要...

    geotools对wms的实现支持

    GeoTools 是一个遵循 OGC 规范的开源 GIS 工具包,提供了地理信息数据读写、处理、坐标转换、查询分析、格式化输出等多个方面的功能。在 GeoTools 的基础上,我们可以实现一个简单的 WMS(Web Map Service),本文将...

    geotools学习(一)IntelliJ IDEA搭建快速入门示例.pdf

    ### GeoTools 学习系列(一):IntelliJ IDEA 搭建快速入门示例 #### 一、概述 GeoTools 是一个开源 Java 库,用于地理空间数据的处理和展示,支持多种地理空间数据格式。对于初学者来说,熟悉如何在开发环境中...

    geotools相关jar包

    GeoTools是一个开源的Java库,专门用于处理地理空间数据,它是基于Open Geospatial Consortium (OGC)标准的实现。...通过不断的实践和学习,开发者可以掌握GeoTools的使用,从而高效地开发GIS应用。

    geotools依赖包

    GeoTools是一个开源的Java库,专门用于处理地理空间数据。这个“geotools依赖包”包含了一组模块,用于支持各种地理信息系统(GIS)...对于初学者,建议从官方文档和示例代码入手,逐步掌握GeoTools的使用方法和技巧。

    geotools18.4开发离线jar包

    GeoTools是一个开源的Java库,专门用于处理地理信息系统(GIS)的数据和任务。它提供了大量的API和工具,使得开发者能够轻松地在应用程序中集成地理空间数据处理功能。本次我们关注的是GeoTools的18.4版本,这是一个...

    GeoTools API

    org.geotools org.geotools.arcsde org.geotools.arcsde.data org.geotools.arcsde.data.view org.geotools.arcsde.filter org.geotools.arcsde.jndi org.geotools.arcsde.logging org.geotools.arcsde....

    geotools依赖.rar

    8. **JUnit** 和 **Mockito**:测试框架,用于确保GeoTools的代码质量,通过编写和执行单元测试来验证功能的正确性。 在实际的构建过程中,开发者需要配置Maven的本地仓库路径指向解压后的“repository”目录,这样...

    geoTools所需jar包

    总结起来,这个"geoTools所需jar包"是为了简化开发者的使用流程,避免手动编译GeoTools的复杂性。通过直接引用这些jar,开发者可以快速地在项目中利用GeoTools的功能,进行地理空间数据的处理和应用开发。

    geotools-bin,24.2,版本bin包

    这个"geotools-bin,24.2,版本bin包"包含了GeoTools库的二进制文件,使得开发者能够轻松地在Java应用程序中集成GIS功能。这个版本号24.2代表着它是该库的一个稳定版本,通常会包含一些新特性和错误修复。 GeoTools库...

    geotools-8.0下载

    GeoTools是开源的Java库,专门用于处理地理信息系统(GIS)的数据和标准。这个压缩包“geotools-8.0-bin.zip”包含了GeoTools的8.0版本,这是一个强大的工具集,允许开发人员在Java环境中集成和操作地理数据。JIS...

Global site tag (gtag.js) - Google Analytics