geotools 实例

通过FactoryFinder创建实例

1.  通过FactoryFinder在文件中找到Factory的链接(.getFactory)

2.  通过Factory创建实例对象(Feature,Filters……)

3.  对实例对象进行操作

打开shapefile文件(Quickstart)

public class Quickstart {

 

    /**

     * GeoTools Quickstart demo application.Prompts the user for a shapefile and displays its

     * contents on the screen in a map frame

     */

    public static void main(String[] args) throws Exception {

        // display adata store file chooser dialog for shapefiles

        File file =JFileDataStoreChooser.showOpenFile(“shp”, null);

        if (file == null) {

            return;

        }

 

        FileDataStore store =FileDataStoreFinder.getDataStore(file);

        SimpleFeatureSource featureSource = store.getFeatureSource();

 

        // Create amap content and add our shapefile to it

        MapContent map = new MapContent();

        map.setTitle(“Quickstart”);

       

        Style style = SLD.createSimpleStyle(featureSource.getSchema());

        Layer layer = new FeatureLayer(featureSource, style);

        map.addLayer(layer);

 

        // Now displaythe map

        JMapFrame.showMap(map);

    }

 

}

 

1.  通过JFileDataStoreChooseer打开文件(特定后缀名)–出现打开文件对话框

——gt-swing.jar

2.  通过StoreFinder获取DataStore

3.  在DataStore获取SimpleFeatureSource

4.  新建FeatureLayer,参数需要featureSource/collection,style

5.  新建MapContent地图容器

6.  加载图层

7.  显示地图

将CVS文件转为shapefile文件并导出

 

思路:(打开cvs文件,)定义新shp文件类型,读取cvs文件数据生成要素(个体),再将要素存到数据集;创建新shp文件,将其指定为工作工厂,将数据集中数据写入。

 

用到的jar包(gt-shapefile,gt-epsg-hsql,gt-swing)

不能直接把所以jar包导入,会报错(org.opengis.referencing.FactoryExceptoin:Fail to connect to the EPSGdatabase)。

另外的可能解决办法:用Maven新建项目(jar包将自己检查和精简),需要在pom.xml中设置需要依赖的jar包名称等。

1.  通过JFileDataStoreChooseer打开文件(特定后缀名)–出现打开文件对话框

——gt-swing.jar

“the_geom:Point:srid=4326,”+ // <- the geometry attribute: Point type,SRID=4326表示坐标系为WGS84。ogc标准中空间参照系统的SRid(Spatial Reference System identifier)与EPSG的空间参照系统id相一致。4326为WGS84的WKID。

2.  通过DataUtilities类创建shp文件的类型以及所包含字段

——gt-main.jar

DataUtilities.createType(typeName, specification )

featureType一旦被创建便无法修改,只能通过复制获得一个subType

点要素的类型名称为location

另外一种创建tpye的方式:SimpleFeatureTypeBuilder

优点:

可定义坐标系、定义字段长度

    /**
     * Here is how you can use a SimpleFeatureType builder to create the schema for your shapefile
     * dynamically.
     * <p>
     * This method is an improvement on the code used in the main method above (where we used
     * DataUtilities.createFeatureType) because we can set a Coordinate Reference System for the
     * FeatureType and a a maximum field length for the 'name' field dddd
     */
    private static SimpleFeatureType createFeatureType() {

 
        SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
        builder.setName("Location");
        builder.setCRS(DefaultGeographicCRS.WGS84); // <- Coordinate reference system

 
        // add attributes in order
        builder.add("the_geom", Point.class);
        builder.length(15).add("Name", String.class); // <- 15 chars width for name field
        builder.add("number",Integer.class);
        
        // build the type
        final SimpleFeatureType LOCATION = builder.buildFeatureType();

 
        return LOCATION;
    }

 

3.  读取csv文件中每行的信息,通过geometryFactory(通过JTSFactoryFinder获得)生成几何图形(.createpoint),并通过featureBuilder添加要素的属性新建(.add)最后创建要素。

4.  创建shapefile文件,并获得生成的shp文件(路径)[A1] 

5.  通过dataStoreFactory创建ShapefileDataStore(需要新建的shp文件的空间索引,通过Map<String, Serializable>获得空间索引),并定义其类型。

6.  获得featuresource再将其赋值到featurestore(featuresource只读文件,featurestore提供读写功能)

7.  通过SimpleFeatureCollection获得所有要素

8.  通过Transaction(修改数据的接口,作用于featurestore)将数据写入shapefile

 

生成缓冲区

用Geometry中Buffer的方法
public Geometry buffer(double distance),和arcgis 中设置的一样(arcgis中distance单位选择unkonw—使用输入要素空间参考的线性单位)。

(在jts-javadoc中可以找到)

如:

//缓冲区

Polygon polygon =(Polygon) point.buffer(10);

按照生成shp文件的方法,生成Polygon类型的。

 

几何坐标参考系

Caused by: org.geotools.factory.FactoryNotFoundException: No factory of kind”CRSAuthorityFactory” found.

要素属性检索

1.  主窗体设计JFrame

注意:

[1]窗体关闭时的响应动作,setDefaultCloseOperation

[2]对窗体添加组件需用到getContentPane()

[3]调整此窗口的大小,以适合其子组件的首选大小和布局。pack();

[4]菜单栏分割线。fileMenu.addSeparator();

[5]JTable需要设置model,通过tablemodel对数据进行操作。

[6]对按钮添加点击事件的方法:如:

fileMenu.add(new SafeAction(“Open shapefile…”) {

            public void action(ActionEvent e) throws Throwable {

                connect(new ShapefileDataStoreFactory());

            }

       });

实例中包含:文本输入框、表格(含滚动条)、选择菜单、下拉选择列表

 

2.  连接数据源,使用DataStoreFactorySpi用于创建数据源仓库

3.  JDataStoreWizard用于打开向导(根据不同DataStore的类型而不同)。适用于 shapefile 或 PostGIS 数据库对话框。需要传入DataStoreFactorySpi参数。

4.  通过JDataStoreWizard获得连接参数,返回值为Map<String, Object>,用于获得datastore。

dataStore =DataStoreFinder.getDataStore(connectionParameters);

5.  对属性表进行筛选

Typename->datastore->getfeaturesource

通过CQL检索语言获得Filter

-à SimpleFeatureCollection features =source.getFeatures(filter);

通过FeatureCollectionTableModel将检索到的SimpleFeatureCollection加进去,

最后可以通过setmodel方法将数据加到jtable中。

6.  统计要素个数

SimpleFeatureCollection.size();

7.  只获取筛选出来的数据的某些属性字段(Query和Filter的区别)

[1]获取字段名(不能直接输入会报错)

通过FeatureType获取。

FeatureTypeschema = source.getSchema();

A.  获取几何属性字段名

schema.getGeometryDescriptor().getLocalName();

B.  获取属性字段名

schema.getDescriptors()—获得所有字段名的集合

遍历写法

for(PropertyDescriptor pro:schema.getDescriptors()){

// PropertyDescriptor是schema.getDescriptors()的其中一个对象,可采用这种方式进行遍历

           if(pro.getName().toString().equals(“the_geom”)){continue;}

           name=pro.getName().toString();//需要将类型转为string

           break;

        }

[2]Query筛选函数:Query query = newQuery(typeName, filter, new String[] {geometryAttributeName,name});

[3]SimpleFeatureCollection features =source.getFeatures(query);

8.  查询语句:

如:

CNTRY_NAME = ‘France’

POP_RANK >= 5

BBOX(the_geom, 110, -45, 155, -10)// 选择所有功能区内北临 110-155 °W,10-45 °S (在澳大利亚附近的松散框) 的边界框查询。

9.  构造弹窗,提供可选的属性字段

[1]定义模态对话框(JDialog),传入参数为:父窗体、featureType

[2]新建属性字段字符串数组:properties = new String[size];

[3]新建container容器,JPanel

[4]需要用到的组件:JCheckBox,JButton

[5]遍历所有属性字段名,PropertyDescriptor pro : schema.getDescriptors()

获取所有被选中属性字段的字段名称:

int j = 0;

for(Component c : checkPanel.getComponents()) {

    if (c instanceof JCheckBox) {

       if (((JCheckBox) c).isSelected()&& j < size)// 是否被选中

           {

               properties[j]= ((JCheckBox) c).getText();

              j++;

           }

       }

}

[6]销毁窗体,释放部分内存。Dispose();

10. 

 

 

设置样式

直接使用设置样式对话框

SimpleFeatureType schema =(SimpleFeatureType)featureSource.getSchema();

        //会根据不同的几何图形而不同

returnJSimpleStyleDialog.showDialog(null, schema);//返回值为style

打开SLD文件配置

1.        新建sld解析

SLDParser  tylereader = new SLDParser(styleFactory, sld);

2.        解析读取样式

Style[] style =stylereader.readXML();

3.        取tyle[0]

自定义样式

1.        创建symbolizer(通过stylefactory.create…)

[1]      LineSymbolizer

方法:StyleFactory.createLineSymbolizercreateLineSymbolizer(Strokestroke[A2] , StringgeometryPropertyName)

a)     创建stroke的方法(三种):

1)     createStroke(Expression[A3]  color,Expression width),颜色、宽度

2)     createStroke(Expression color, Expressionwidth, Expression opacity),颜色、宽度、不透明度

3)     createStroke(Expression color, Expressionwidth, Expression opacity, Expression lineJoin, Expression lineCap, float[]dashArray, Expression dashOffset, Graphic graphicFill, Graphic graphicStroke)

                                            i.         lineJoin

设置线条转角样式(mitre(斜接面)(默认值)、bevel(斜面)[A4] 、round(圆形))

                                           ii.         lineCap

设置线条端点形状(butt、square[A5] 、round)

                                          iii.         dashArray

轮廓的虚线的间隔样式({4,6}、{10.10})

                                          iv.         dashOffset

设定虚线时虚实间隔中的其实的

                                           v.         graphicFill

设置填充图案,图案平铺填充;若为null,则以颜色填充

                                          vi.         graphicStroke

用样式点划线,会忽略线的宽度。StyleFactory.graphicStroke(……)

graphicStroke(

List<GraphicalSymbol>symbols,//只能加入一个symbol,加入新的样式前线graphic.graphicalSymbols().clear();,List<GraphicalSymbol> symbols=graphic.graphicalSymbols();

                    Expression opacity,

                    Expression size,

                    Expression rotation,//旋转角度(顺时针)

                    AnchorPoint anchorPoint,//旋转中心

                    Displacement displacement,//多用于呈现一个点附近的文本样签,默认(0,0),styleFactory.createDisplacement

                    Expression initialGap,//第一个图像相对于开始的距离

                    Expression gap)//两个graphic之间的距离

b)      

[2]      PolygonSymbolizer

StyleFactory.createPolygonSymbolizer(Strokestroke, Fill fill, String geometryPropertyName)

a)        styleFactory.createStroke

b)        styleFactory.createFill

[3]      PointSymbolizer

createPointSymbolizer(Graphicgraphic, String geometryPropertyName)

a)        创建mark(通过styleFactory.get___Mark())

                                                                  i.             Mark.setStroke//轮廓线样式

                                                                ii.             Mark.setfill//填充

                                                               iii.             Mark.setWellKonwName(string[A6] )//会覆盖i设置的样式

                                                               iv.             Mark. setExternalMark(arg0)//加载png,svg作填充

b)        创建graphic

Graphic graphic= sf.createDefaultGraphic();

c)        将mark加进graphic中

graphic.graphicalSymbols().clear();

graphic.graphicalSymbols().add(mark_end);

2.        创建rule(通过stylefactory.createrule())

3.        将symbolizer加进rule中(rule.add(symbolizer))

a)        对同一几何要素的不同特征设置样式(如画箭头线)

                                                    i.             新建FilterFunction_endPoint

                                                  ii.             得到数据的几何类型,加如list<expression>

Expression attribute =ff.property(schema.getGeometryDescriptor().getName());

        List<Expression> params=new ArrayList<Expression>();

        params.add(attribute);

                                                 iii.             设置检索终点的作用对象

      endPoint.setParameters(params);

                                                 iv.             设置样式的作用几何对象

 end_psym.setGeometry(endPoint);

                                                  v.             将symbol添加到rule中

rule.symbolizers().add(end_psym);

b)         

4.        创建FeatureTypeStyle,传入rule做参数。

FeatureTypeStylefts = sf.createFeatureTypeStyle(new Rule[]{rule});

a)        对不同要素赋予不同样式(进行筛选)

RuleselectedRule = createRule(SELECTED_COLOUR, SELECTED_COLOUR);

        selectedRule.setFilter(ff.id(IDs));

        Rule otherRule =createRule(LINE_COLOUR, FILL_COLOUR);

        otherRule.setElseFilter(true);

 

        FeatureTypeStyle fts =sf.createFeatureTypeStyle();

        fts.rules().add(selectedRule);

        fts.rules().add(otherRule);

5.        创建style

Style style =sf.createStyle();

6.        将刚刚新建的FeatureTypeStyle加到style中,style.featureTypeStyles().add(fts);

FilterFactory.literal(……)

这个接口的实例提供一个常数,返回值为literal可以用在表达式的值。

传入参数:

Boolean

Byte

Char

Double

Float

Int

Long

Object

Short

 

 

 

 

 

 

 

Color,

String……

 

 

建立sld样式文件

1.        使用udig新建设置样式后保存即可。

不同的FactoryFinder接口所对应能找到的工厂类型

CommonFactoryFinder

  • FilterFactory
  • StyleFactory
  • Function
  • FeatureLockFactory
  • FileDataStore – factory used to work with file datastores
  • FeatureFactory – factory used to create features
  • FeatureTypeFactory – factory used to create feature type description
  • FeatureCollections – factory used to create feature collection

对应于矢量要素(Feature)的FactoryFinder

  • DataAccessFinder – listing DataAccessFactory for working with feature data
  • DataStoreFinder – lists DataStoreFactorySpi limited to simple features
  • FileDataStoreFinder – Create of FileDataStoreFactorySpi instances limited to file formats

对应于栅格(Coverage)的FactoryFinder

  • GridFormatFinder – access to GridFormatFactorySpi supporting raster formats
  • CoverageFactoryFinder – access to GridCoverageFactory

JTSFactoryFinder

  • GeometryFactory
  • PrecisionModel

ReferencingFactoryFinder

  • DatumFactory
  • CSFactory
  • DatumAuthorityFactory
  • CSAuthorityFactory
  • CRSAuthorityFactory
  • MathTransformFactory
  • CoordinateOperationFactory
  • CoordinateOperationAuthorityFactory

遍历对象:FeatureIterator和FeatureVisitor异同

FeatureIterator

FeatureVisitor

使用完毕需要调用.close()

多用于计算,数据转换

不适用于大数据量GIS

 

所含方法:

.hasnext();

.next();

.close();

所含方法:

.visitor();

转载自:https://blog.csdn.net/admin_fx/article/details/81566124

You may also like...

退出移动版