geotools 使用 部分代码总结

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

以下是部分功能总结:

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

  1. private static
    void conn(String dbtype, String host, String port, 
  2.             String database, String userName, String password) { 
  3.         Map<String, Object> params =
    new
    HashMap<String, Object>(); 
  4.         // params.put(PostgisNGDataStoreFactory.DBTYPE.key, “postgis”);    // 两种代码方式 
  5.         // params.put(PostgisNGDataStoreFactory.HOST.key, “localhost”); 
  6.         // params.put(PostgisNGDataStoreFactory.PORT.key, new Integer(5432)); 
  7.         // params.put(PostgisNGDataStoreFactory.DATABASE.key, “postgis”); 
  8.         // params.put(PostgisNGDataStoreFactory.SCHEMA.key, “public”); 
  9.         // params.put(PostgisNGDataStoreFactory.USER.key, “postgres”); 
  10.         // params.put(PostgisNGDataStoreFactory.PASSWD.key, “root”); 
  11.         params.put(PostgisNGDataStoreFactory.DBTYPE.key, dbtype); 
  12.         params.put(PostgisNGDataStoreFactory.HOST.key, host); 
  13.         params.put(PostgisNGDataStoreFactory.PORT.key,
    new
    Integer(port)); 
  14.         params.put(PostgisNGDataStoreFactory.DATABASE.key, database); 
  15.         params.put(PostgisNGDataStoreFactory.SCHEMA.key,
    “public”
    ); 
  16.         params.put(PostgisNGDataStoreFactory.USER.key, userName); 
  17.         params.put(PostgisNGDataStoreFactory.PASSWD.key, password); 
  18.         try
  19.             pgDatastore = DataStoreFinder.getDataStore(params); 
  20.             if (pgDatastore !=
    null) { 
  21.                 System.out.println(“系统连接到位于:” + host +
    “的空间数据库” + database 
  22.                         + “成功!”); 
  23.             } else
  24.                 System.out.println(“系统连接到位于:” + host +
    “的空间数据库” + database 
  25.                         + “失败!请检查相关参数”); 
  26.             } 
  27.         } catch (IOException e) { 
  28.             e.printStackTrace(); 
  29.             System.out.println(“系统连接到位于:” + host +
    “的空间数据库” + database 
  30.                     + “失败!请检查相关参数”); 
  31.         } 
  32.  
  33.     } 
  34. 调用方法为:conn(“postgis”, “localhost”,
    5432, “postgis”,
    “postgres”, “root”); 
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、图层的操作

  1. 2.1 查询 
  2. public static ArrayList<SimpleFeature> queryMethod(String filterStr, 
  3.             String layerName) { 
  4.         //pgDatastore为上文连接数据库获取相当于AE中的workspace 
  5.         //SimpleFeatureSource相当于AE中的featureClass 
  6.         SimpleFeatureSource featureSource =pgDatastore.getFeatureSource(layerName);  
  7.         ArrayList<SimpleFeature> featureList =
    new
    ArrayList<SimpleFeature>(); 
  8.         if(featureSource==null
  9.             return featureList; 
  10.         try
  11.             Filter filter; 
  12.             filter = CQL.toFilter(filterStr); // filterStr形式 如  name=’武汉大学’ or code like ‘tt123%’ 
  13.             SimpleFeatureCollection result = featureSource.getFeatures(filter); 
  14.  
  15.             FeatureIterator<SimpleFeature> itertor = result.features(); 
  16.             while (itertor.hasNext()) { 
  17.                 SimpleFeature feature = itertor.next(); 
  18.                 featureList.add(feature); 
  19.             } 
  20.             itertor.close(); 
  21.             return featureList; 
  22.         } catch (CQLException e) { 
  23.             // TODO Auto-generated catch block 
  24.             e.printStackTrace(); 
  25.         } catch (IOException e) { 
  26.             // TODO Auto-generated catch block 
  27.             e.printStackTrace(); 
  28.         } 
  29.         return null
  30.     } 
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;
	}
  1. 2.2 要素操作  对上面4.1中的 SimpleFeature操作 
  2. //获取feature的geometry 
  3. Geometry geo=(Geometry) feature.getDefaultGeometry(); 
  4. //获取geometry中的坐标 这里用string的方式保存 
  5. int geoUnm = geo.getNumGeometries(); 
    // 一个geometry可能含有n个geometry 
  6. for (int i =
    0; i < geoUnm; i++) { 
  7.     Geometry singleGeo = geo.getGeometryN(i);
    //获取其中每一个geometry
     
  8.     int pointCount = singleGeo.getNumPoints(); 
  9.     Coordinate[] coords = singleGeo.getCoordinates(); 
  10.     for (int j =
    0; j < pointCount; j++) { 
  11.         if (j == pointCount –
    1
  12.             sBuilder.append(coords[j].x + “,” + coords[j].y); 
  13.         else
  14.             sBuilder.append(coords[j].x + “,” + coords[j].y 
  15.                                     +
    “;”
    ); 
  16.         } 
  17.     } 
  18.     if (i != geoUnm – 1) { 
  19.         sBuilder.append(“|”); 
  20.     } 
  21. }  
  22. //获取feature中的属性 
  23. feature.getAttribute(arg0); 
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);
  1. 2.3 拓扑查询 
  2. public static Filter getGeoFilter(FilterFactory2 ff,               
    //构建拓扑查询的filter 
  3.             String geometryAttributeName, Geometry refGeo, 
  4.             SpatialReltionType.TopoRelTypeEnum relType) {  
    //这个SpatialReltionType是我自己定义的。。。
     
  5.  
  6.         switch (relType) { 
  7.         case intersect: 
  8.             return ff.intersects(ff.property(geometryAttributeName), ff 
  9.                     .literal(refGeo)); 
  10.         case contains: 
  11.             return ff.contains(ff.property(geometryAttributeName), ff 
  12.                     .literal(refGeo)); 
  13.         case within: 
  14.             return ff.within(ff.property(geometryAttributeName), ff 
  15.                     .literal(refGeo)); 
  16.         case cross: 
  17.             return ff.crosses(ff.property(geometryAttributeName), ff 
  18.                     .literal(refGeo)); 
  19.         case overlaps: 
  20.             return ff.overlaps(ff.property(geometryAttributeName), ff 
  21.                     .literal(refGeo)); 
  22.         case touches: 
  23.             return ff.touches(ff.property(geometryAttributeName), ff 
  24.                     .literal(refGeo)); 
  25.         case equals: 
  26.             return ff.equals(ff.property(geometryAttributeName), ff 
  27.                     .literal(refGeo)); 
  28.         case disjoint: 
  29.             return ff.disjoint(ff.property(geometryAttributeName), ff 
  30.                     .literal(refGeo)); 
  31.         default
  32.             return null
  33.         } 
  34.     } 
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;
		}
	}
  1. // 普通的拓扑查询 
  2. public static ArrayList<Geometry> topoQueryMethod(Geometry refGeo, 
  3.             String layerName, SpatialReltionType.TopoRelTypeEnum relType) { 
  4.         ArrayList<SimpleFeature> featurelist=new ArrayList<SimpleFeature>(); 
  5.         FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(null); 
  6.         SimpleFeatureSource featureSource=pgDatastore.getFeatureSource(layerName);  
  7.      
  8.         SimpleFeatureType schema = featureSource.getSchema(); 
  9.         String geometryAttributeName = schema.getGeometryDescriptor().getLocalName(); 
  10.         Filter filter1= getGeoFilter(ff,geometryAttributeName, refGeo, relType);   
    //上面的方法 
  11.         SimpleFeatureCollection result=null
  12.         try
  13.             result = featureSource.getFeatures(filter1); 
  14.         } catch (IOException e) { 
  15.             // TODO Auto-generated catch block 
  16.             e.printStackTrace(); 
  17.         } 
  18.         if(result==null
  19.             return
    null
  20.         FeatureIterator<SimpleFeature> itertor = result.features(); 
  21.         while (itertor.hasNext()) { 
  22.             SimpleFeature feature = itertor.next(); 
  23.             featurelist.add(feature); 
  24.         } 
  25.         //这个方法是将feature转为geometry 自己定义的 
  26.         return SpatialUtil.ConverToGeoList(featurelist);   
  27.     } 
// 普通的拓扑查询
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);  
	}
  1. //联合属性的拓扑查询 
  2. public static ArrayList<Geometry> topoQueryMethod(Geometry refGeo, 
  3.             String queryName, String layerName, 
  4.             SpatialReltionType.TopoRelTypeEnum relType) { 
  5.         FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(null); 
  6.         ArrayList<SimpleFeature> featurelist=new ArrayList<SimpleFeature>(); 
  7.         SimpleFeatureSource featureSource=pgDatastore.getFeatureSource(layerName);  
  8.      
  9.         SimpleFeatureType schema = featureSource.getSchema(); 
  10.         String geometryAttributeName = schema.getGeometryDescriptor().getLocalName(); 
  11.         Filter filter1= SpatialUtil.getGeoFilter(ff,geometryAttributeName, refGeo, relType);     
  12.         Filter filter2=null
  13.         try
  14.             filter2=CQL.toFilter(“StandName = ‘”+queryName+“‘”); 
  15.         } catch (CQLException e1) { 
  16.             // TODO Auto-generated catch block 
  17.             e1.printStackTrace(); 
  18.         } 
  19.         List<Filter> match = new ArrayList<Filter>(); 
  20.         match.add(filter1); 
  21.         match.add(filter2); 
  22.         Filter filter = ff.and(match); 
  23.  
  24.         SimpleFeatureCollection result=null
  25.         try
  26.             result = featureSource.getFeatures(filter); 
  27.         } catch (IOException e) { 
  28.             // TODO Auto-generated catch block 
  29.             e.printStackTrace(); 
  30.         } 
  31.         if(result==null
  32.             return null
  33.         FeatureIterator<SimpleFeature> itertor = result.features(); 
  34.         while (itertor.hasNext()) { 
  35.             SimpleFeature feature = itertor.next(); 
  36.             featurelist.add(feature); 
  37.         } 
  38.         return SpatialUtil.ConverToGeoList(featurelist); 
  39.          
  40.     } 
//联合属性的拓扑查询
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,编辑图层

  1. 3.1 添加要素 
  2.     //添加一个feature到图层中 在添加前要确定构造featureType 
  3.     public static SimpleFeatureType createFeatureType(String typeName,Class type) { 
  4.         SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder(); 
  5.         builder.setName(typeName); 
  6.         builder.setCRS(DefaultGeographicCRS.WGS84);
    // <- Coordinate reference
     
  7.                                                    
    // system
     
  8.         builder.add(“the_geom”, type); 
    //这个为地理属性字段 postgis中为 the——geom 
  9.  
  10.         builder.add(“StandName”, String.class);
    // 这是其他属性字段 自己定义的….                          
     
  11.         // build the type 
  12.         final SimpleFeatureType TYPE = builder.buildFeatureType(); 
  13.  
  14.         return TYPE; 
  15.     } 
  16.      
  17.     //添加到图层的图层名,添加的要素空间属性和要素的某属性名 
  18.     public static
    boolean addFeature(String layerName,Geometry geo,String featureName){  
  19.         String type=geo.getGeometryType(); 
  20.         Class TypeClass=null
  21.         if(type.toLowerCase().equals(“point”)){ 
  22.             TypeClass=Point.class
  23.         }else if(type.toLowerCase().equals(“polygon”)){ 
  24.             TypeClass=Polygon.class
  25.         }else if(type.toLowerCase().equals(“polyline”)){ 
  26.             TypeClass=Polyline.class
  27.         }else if(type.toLowerCase().equals(“multipolygon”)){ 
  28.             TypeClass=MultiPolygon.class
  29.         } 
  30.         SimpleFeatureType featureType=createFeatureType(layerName,TypeClass); 
  31.          SimpleFeatureCollection collection = FeatureCollections.newCollection(); 
  32.  
  33.         SimpleFeatureBuilder featureBuilder =
    new
    SimpleFeatureBuilder(featureType); 
  34.          /* Longitude (= x coord) first ! */ 
  35.         GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null); 
  36.       
  37.         featureBuilder.add(geo); 
  38.         featureBuilder.add(featureName); 
  39.         
  40.         SimpleFeature feature = featureBuilder.buildFeature(null); 
  41.         collection.add(feature); 
  42.  
  43.         FeatureSource featureSource=pgDatastore.getFeatureSource(layerName);  
  44.         if (featureSource instanceof SimpleFeatureStore) { 
  45.             SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource; 
  46.             Transaction transaction = new DefaultTransaction(“create”); 
  47.             featureStore.setTransaction(transaction); 
  48.             try
  49.                 featureStore.addFeatures(collection); 
  50.                 transaction.commit(); 
  51.                 return
    true
  52.  
  53.             } catch (Exception problem) { 
  54.                 problem.printStackTrace(); 
  55.                 try
  56.                     transaction.rollback(); 
  57.                 } catch (IOException e) { 
  58.                     // TODO Auto-generated catch block 
  59.                     e.printStackTrace(); 
  60.                 } 
  61.  
  62.             } finally
  63.                 try
  64.                     transaction.close(); 
  65.                 } catch (IOException e) { 
  66.                     // TODO Auto-generated catch block 
  67.                     e.printStackTrace(); 
  68.                 } 
  69.             } 
  70.           
  71.         } else
  72.             System.out.println(layerName + ” does not support read/write access”);       
  73.         } 
  74.         return false
  75.     } 
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;
	}
  1.   3.2 修改要素 
  2. / 修改feacode为XX的要素的名字为featureName 地理方位为geo  (feacode StandName为你的属性字段自定义) 
  3. public static
    boolean modifyFeature(String layerName,Geometry geo,String featureName,String FeaCode){ 
  4.   FeatureSource featureSource=pgDatastore.getFeatureSource(layerName);  
  5.        if (featureSource
    instanceof SimpleFeatureStore) { 
  6.            SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource; 
  7.            Transaction transaction =
    new
    DefaultTransaction(“create”); 
  8.            featureStore.setTransaction(transaction); 
  9.            try
  10.             String filterStr=“FeaCode= ‘”+FeaCode+“‘”
  11.             String[] names=new String[2]; 
  12.             names[0]=“StandName”
  13.             names[1]=“the_geom”
  14.             Object[] values=new Object[2]; 
  15.             values[0]=featureName; 
  16.             values[1]=geo; 
  17.             featureStore.modifyFeatures(names, values, CQL.toFilter(filterStr)); 
  18.             
  19.                
  20.                transaction.commit(); 
  21.                   return
    true
  22.            } catch (Exception problem) { 
  23.                problem.printStackTrace(); 
  24.                try
  25.                 transaction.rollback(); 
  26.             } catch (IOException e) { 
  27.                 // TODO Auto-generated catch block 
  28.                 e.printStackTrace(); 
  29.             } 
  30.  
  31.            } finally
  32.                try
  33.                 transaction.close(); 
  34.             } catch (IOException e) { 
  35.                 // TODO Auto-generated catch block 
  36.                 e.printStackTrace(); 
  37.             } 
  38.            } 
  39.          
  40.        } else
  41.            System.out.println(layerName +
    ” does not support read/write access”
    );       
  42.        } 
  43.     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方法:这里转载一个别人写的比较好的

  1. 4.1构建点 
  2. public Point createPoint(){   
  3.         Coordinate coord = new Coordinate(109.013388,
    32.715519);   
  4.         Point point = geometryFactory.createPoint( coord );   
  5.         return point;   
  6.     }  
  7. public Point createPointByWKT()
    throws ParseException{   
  8.         WKTReader reader = new WKTReader( geometryFactory );   
  9.         Point point = (Point) reader.read(“POINT (109.013388 32.715519)”);   
  10.         return point;   
  11.     }  
  12. public MultiPoint createMulPointByWKT()throws ParseException{   
  13.         WKTReader reader = new WKTReader( geometryFactory );   
  14.         MultiPoint mpoint = (MultiPoint) reader.read(“MULTIPOINT(109.013388 32.715519,119.32488 31.435678)”);   
  15.         return mpoint;   
  16.     }  
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;  
    } 
  1. 4.2 构建线 
  2. public LineString createLine(){   
  3.         Coordinate[] coords  = new Coordinate[] {new Coordinate(2,
    2), new Coordinate(2,
    2)};   
  4.         LineString line = geometryFactory.createLineString(coords);   
  5.         return line;   
  6.     }   
  7. public LineString createLineByWKT()
    throws ParseException{   
  8.         WKTReader reader = new WKTReader( geometryFactory );   
  9.         LineString line = (LineString) reader.read(“LINESTRING(0 0, 2 0)”);   
  10.         return line;   
  11.     }   
  12. public MultiLineString createMLine(){   
  13.         Coordinate[] coords1  = new Coordinate[] {new Coordinate(2,
    2), new Coordinate(2,
    2)};   
  14.         LineString line1 = geometryFactory.createLineString(coords1);   
  15.         Coordinate[] coords2  = new Coordinate[] {new Coordinate(2,
    2), new Coordinate(2,
    2)};   
  16.         LineString line2 = geometryFactory.createLineString(coords2);   
  17.         LineString[] lineStrings = new LineString[2];   
  18.         lineStrings[0]= line1;   
  19.         lineStrings[1] = line2;   
  20.         MultiLineString ms = geometryFactory.createMultiLineString(lineStrings);   
  21.         return ms;   
  22.     }   
  23. public MultiLineString createMLineByWKT()throws ParseException{   
  24.         WKTReader reader = new WKTReader( geometryFactory );   
  25.         MultiLineString line = (MultiLineString) reader.read(“MULTILINESTRING((0 0, 2 0),(1 1,2 2))”);   
  26.         return line;   
  27.     }  
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;  
    } 
  1. 4.3 构建多边形 
  2. public Polygon createPolygonByWKT()
    throws ParseException{   
  3.         WKTReader reader = new WKTReader( geometryFactory );   
  4.         Polygon polygon = (Polygon) reader.read(“POLYGON((20 10, 30 0, 40 10, 30 20, 20 10))”);   
  5.         return polygon;   
  6.     }   
  7. public MultiPolygon createMulPolygonByWKT()
    throws ParseException{   
  8.         WKTReader reader = new WKTReader( geometryFactory );   
  9.         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)))”);   
  10.         return mpolygon;   
  11.     }   
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;  
    }  
  1. 4.4 构建geo集合 
  2. public GeometryCollection createGeoCollect()
    throws ParseException{   
  3.         LineString line = createLine();   
  4.         Polygon poly =  createPolygonByWKT();   
  5.         Geometry g1 = geometryFactory.createGeometry(line);   
  6.         Geometry g2 = geometryFactory.createGeometry(poly);   
  7.         Geometry[] garray = new Geometry[]{g1,g2};   
  8.         GeometryCollection gc = geometryFactory.createGeometryCollection(garray);   
  9.         return gc;   
  10.     }  
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;  
    } 
  1. 4.5 构建圆 
  2. public Polygon createCircle(double x,
    double y, final
    double RADIUS){   
  3.         final int SIDES =
    32;//圆上面的点个数 
     
  4.         Coordinate coords[] = new Coordinate[SIDES+1];   
  5.         for( int i =
    0; i < SIDES; i++){   
  6.             double angle = ((double) i / (double) SIDES) * Math.PI *
    2.0;   
  7.             double dx = Math.cos( angle ) * RADIUS;   
  8.             double dy = Math.sin( angle ) * RADIUS;   
  9.             coords[i] = new Coordinate( (double) x + dx, (double) y + dy );   
  10.         }   
  11.         coords[SIDES] = coords[0];   
  12.         LinearRing ring = geometryFactory.createLinearRing( coords );   
  13.         Polygon polygon = geometryFactory.createPolygon( ring,
    null );   
  14.         return polygon;   
  15.     }   
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’);

转载自:https://blog.csdn.net/sxausgyy/article/details/8150989

You may also like...