用geotools在内存新建一个layer并显示

通常是通过读取某个shp文件,将shp中的图层显现出来,如下:

	File file = JFileDataStoreChooser.showOpenFile("shp", null);
        if (file == null) {
            return;
        }

        FileDataStore store = FileDataStoreFinder.getDataStore(file);
        SimpleFeatureSource featureSource = store.getFeatureSource();

        // Create a map 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);
	JMapFrame.showMap(map);

    现不想读取文件中图层,而利用geotools自己在内存中生成一个layer,并显示,方法如下:(layer中只画了一个polygon)

	MapContent map = new MapContent();
        map.setTitle("Quickstart");
        SimpleFeatureType TYPE = DataUtilities.createType("location","geom:Polygon,name:String");

        DefaultFeatureCollection featureCollection = new DefaultFeatureCollection("internal",TYPE);
        WKTReader2 wkt = new WKTReader2();

        featureCollection.add( SimpleFeatureBuilder.build( TYPE, new Object[]{ wkt.read("POLYGON((20 10, 30 0, 40 10, 30 20, 20 10))"), "name1"}, null) );
        Color color1 = Color.BLUE;
        Color color2 = Color.RED;
        Style style2 = SLD.createPolygonStyle(color1, color2.brighter(), 0.5f);
        Layer layer2 = new FeatureLayer(featureCollection,style2);
        layer2.setVisible(true);
        // Now display the map
        map.addLayer(layer2);
        //FeatureLayer layers = (FeatureLayer) map.layers().get(0);
        //System.out.println(layers);
        JMapFrame.showMap(map);

生成的图层如下:

参考资料:1.http://docs.geotools.org/latest/userguide/library/main/collection.html

   2.http://stackoverflow.com/questions/26882297/add-feature-to-existing-layer-in-geotools

   3.http://osgeo-org.1560.x6.nabble.com/Adding-geometry-to-layer-td4324729.html

转载自:https://blog.csdn.net/arenn/article/details/62882210

You may also like...