I. Project Directory Structure Tree
II. Project Start-up
3. Write to the specified shp file
(1) json data [Post]
{ "name":"test", "path":"c:/test", "geom":"MULTIPOLYGON(((101.870371 25.19228,101.873633 25.188183,101.880564 25.184416,101.886808 25.186028,101.892043 25.189969,101.896592 25.190163,101.903716 25.190785,101.905454 25.193464,101.899897 25.196202,101.894146 25.197911,101.891657 25.19826,101.886078 25.197658,101.884211145538 25.2007060137013,101.88172564506 25.1949712942389,101.87874 25.199619,101.874641 25.200998,101.868547 25.202415,101.863741 25.202415,101.85887 25.202842,101.854557 25.202182,101.852604 25.199736,101.852282 25.19628,101.854492 25.194183,101.855608 25.192668,101.863698 25.192105,101.870371 25.19228)))", "id":1001, "des":"Lake surface" }
(2) Interface call
(3) QGIS view to verify data validity
4. Read the specified shp file and display the content
(1) Interface call
(2) QGIS displays Beijing Palace Museum [shp files in the static folder of the project]
5. Converting a specified shp file to an image file or stream
(1) Interface call ==== Transfer image [png] file
View under CD
(2) Interface call ==== image stream, output to client
6. Core Tools
package com.appleyk.geotools; import com.appleyk.IO.StringTokenReader; import com.appleyk.pojos.ShpDatas; import com.appleyk.pojos.ShpInfo; import com.appleyk.result.ResponseMessage; import com.appleyk.result.ResponseResult; import com.vividsolutions.jts.geom.*; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Polygon; import org.geotools.data.*; import org.geotools.data.shapefile.ShapefileDataStore; import org.geotools.data.shapefile.ShapefileDataStoreFactory; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.feature.FeatureCollection; import org.geotools.feature.FeatureIterator; import org.geotools.feature.simple.SimpleFeatureTypeBuilder; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.map.FeatureLayer; import org.geotools.map.Layer; import org.geotools.map.MapContent; import org.geotools.referencing.crs.DefaultGeographicCRS; import org.geotools.renderer.lite.StreamingRenderer; import org.geotools.styling.SLD; import org.geotools.styling.Style; import org.geotools.swing.JMapFrame; import org.geotools.swing.data.JFileDataStoreChooser; import org.opengis.feature.Property; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.springframework.util.ResourceUtils; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.nio.charset.Charset; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * <p>shapefile Reading and Writing Tool Class </p> * @author Appleyk * @blob https://blog.csdn.net/appleyk * @date Created on 11:54 a.m. 2018-10-12 */ public class ShpTools { /** * Collection Object Constructor */ private static GeometryCreator gCreator = GeometryCreator.getInstance(); /** * boundary */ private static ReferencedEnvelope bounds; // Width of canvas private static final int IMAGE_WIDTH = 2400; // The height of the canvas private static final int IMAGE_HEIGHT = 1200; /** * Read shp content through shp file path * @param filePath * @throws Exception */ public static ShpDatas readShpByPath(String filePath,Integer limit) throws Exception { // A data storage implementation that allows from Shapefiles Read and write ShapefileDataStore shpDataStore = new ShapefileDataStore(new File(filePath).toURI().toURL()); // Setting Code [Preventing Chinese Scrambling] shpDataStore.setCharset(Charset.forName("UTF-8")); // getTypeNames:Get all the geographic layers, and here I just take the first one [if it's a data table, it's the name of the table]. String typeName = shpDataStore.getTypeNames()[0]; System.out.println("shp[Layer) Name:"+typeName); FeatureCollection<SimpleFeatureType, SimpleFeature> result = getFeatures(shpDataStore, typeName); // Iterative feature set FeatureIterator<SimpleFeature> iterator = result.features(); ShpDatas shpDatas = new ShpDatas(); shpDatas.setName(typeName); shpDatas.setShpPath(filePath); buildShpDatas(limit, iterator, shpDatas); iterator.close(); return shpDatas; } /** * Get feature set according to data source and layer name * @param shpDataStore * @param typeName * @return * @throws IOException */ private static FeatureCollection<SimpleFeatureType, SimpleFeature> getFeatures(ShapefileDataStore shpDataStore, String typeName) throws IOException { // Individual references can be made through this interface shapefile,Database tables, etc. Comparisons and constraints with data storage FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = shpDataStore.getFeatureSource(typeName); // One for processing FeatureCollection Utility class. Provide an access FeatureCollection Instance mechanism FeatureCollection<SimpleFeatureType, SimpleFeature> result = featureSource.getFeatures(); System.out.println("Geographical elements [records]:"+result.size()+"individual"); System.out.println("=================================="); return result; } /** * Building shpDatas objects * @param limit * @param iterator * @param shpDatas */ private static void buildShpDatas(Integer limit, FeatureIterator<SimpleFeature> iterator, ShpDatas shpDatas) { // Here we only iterate before limit individual int stop = 0; while (iterator.hasNext()) { if (stop > limit) { break; } // Get a feature SimpleFeature feature = iterator.next(); // Extract the set of attributes in the feature Collection<Property> p = feature.getProperties(); // Traversal property set Map<String,Object> prop = new HashMap<>(); for (Property pro : p) { String key = pro.getName().toString(); String val = pro.getValue().toString(); prop.put(key, val); System.out.println("key[Field:"+key+"\t|| value[Value:"+val); } System.out.println("\n============================ Serial number:"+stop+"\n"); shpDatas.addProp(prop); stop++; } // end Outermost layer while } /** * Write a geometric object into shapefile * @param filePath * @param geometry */ public static void writeShpByGeom(String filePath, Geometry geometry) throws Exception{ ShapefileDataStore ds = getshpDS(filePath, geometry); FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT); // Interface SimpleFeature: A fixed list of values in a known order. SimpleFeatureType Example. SimpleFeature feature = writer.next(); feature.setAttribute("name", "XXXX Name"); feature.setAttribute("path", "c:/test"); feature.setAttribute("the_geom", geometry); feature.setAttribute("id", 1010L); feature.setAttribute("des", "XXXX describe"); System.out.println("========= Write ["+geometry.getGeometryType()+"]Success!========="); // Write in writer.write(); // Close writer.close(); // Release resources ds.dispose(); } /** * Write a geometric object into shapefile * @param shpInfo */ public static ResponseResult writeShpByGeom(ShpInfo shpInfo) throws Exception{ // Special String Parser StringTokenReader reader = new StringTokenReader(); // According to the geometric object wkt String, inverse solution [parsing] Geometry object Geometry geometry = reader.read(shpInfo.getGeom()); // Get shp The directory [folder] where the object is located String path = shpInfo.getPath(); File file = new File(path); if(!file.exists()){ file.mkdir(); } if(!file.isDirectory()){ return new ResponseResult(ResponseMessage.BAD_REQUEST,"path Not a valid folder" ); } String filePath = shpInfo.getPath()+"/"+shpInfo.getName()+".shp"; ShapefileDataStore ds = getshpDS(filePath, geometry); String typeName = ds.getTypeNames()[0]; FeatureWriter<SimpleFeatureType, SimpleFeature> writer ; if(shpInfo.isAppendWrite()){ // Additional Writing of Geometric Objects writer = ds.getFeatureWriterAppend(typeName, Transaction.AUTO_COMMIT); }else{ // Overwriting Geometric Objects writer = ds.getFeatureWriter(typeName, Transaction.AUTO_COMMIT); } // Interface SimpleFeature: A fixed list of values in a known order. SimpleFeatureType Example. SimpleFeature feature = writer.next(); feature.setAttribute("name", shpInfo.getName()); feature.setAttribute("path", shpInfo.getPath()); feature.setAttribute("the_geom", geometry); feature.setAttribute("id", shpInfo.getId()); feature.setAttribute("des", shpInfo.getDes()); System.out.println("========= Write ["+geometry.getGeometryType()+"]Success!========="); // Write in writer.write(); // Close writer.close(); // Release resources ds.dispose(); // Return to the one created successfully shp File path return new ResponseResult(ResponseMessage.OK,filePath); } /** * Get the configured DataStore * @param filePath * @param geometry * @return * @throws IOException */ private static ShapefileDataStore getshpDS(String filePath, Geometry geometry) throws IOException { // 1.Establish shape File object File file = new File(filePath); Map<String, Serializable> params = new HashMap<>(); // 2,Data classes for capturing parameter requirements URLP:url to the .shp file. params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL()); // 3,Create a new data store [if it exists, it is not created] ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params); // 4,Define graphic information and attribute information -- SimpleFeatureTypeBuilder Constructor for Constructing Simple Characteristic Types SimpleFeatureTypeBuilder tBuilder = new SimpleFeatureTypeBuilder(); // 5,Set up -- WGS84:A two-dimensional geographic coordinate reference system, using WGS84 data tBuilder.setCRS(DefaultGeographicCRS.WGS84); tBuilder.setName("shapefile"); // add name tBuilder.add("name", String.class); // Add to shp Name of directory tBuilder.add("path", String.class); // Add a geometric object tBuilder.add("the_geom", geometry.getClass()); // Add one id tBuilder.add("id", Long.class); // Add description tBuilder.add("des", String.class); // Set the feature type for this data store ds.createSchema(tBuilder.buildFeatureType()); // Set encoding ds.setCharset(Charset.forName("UTF-8")); return ds; } /** * Open the shp file to get the map content * @param filePath File path * @param isOpenByChoose Whether to customize opening shp file * @throws Exception */ public static MapContent getMapContentByPath(String filePath,boolean isOpenByChoose,String color) throws Exception{ File file; if(isOpenByChoose){ // 1.1, Data Source Selection shp Extended type file = JFileDataStoreChooser.showOpenFile("shp", null); }else{ // 1.2,Get the file object according to the path file = new File(filePath); } if(file==null){ return null; } // 2,Get the data source of the open file FileDataStore store = FileDataStoreFinder.getDataStore(file); // 3,Setting up the encoding of data source to prevent Chinese scrambling ((ShapefileDataStore)store).setCharset(Charset.forName("UTF-8")); /** * Use FeatureSource to manage element data * Use Style (SLD) management style * Managing Display with Layer * Use MapContent to manage all map-related information */ // 4,with java Object-based access to geographic information -- Elements of Simple Theory SimpleFeatureSource featureSource = store.getFeatureSource(); bounds = featureSource.getBounds(); // 5,Create mapping content and add our shapfile piece in MapContent mapContent = new MapContent(); // 6,Setting the Title of the Container mapContent.setTitle("Appleyk's GeoTools"); Color color1; if(color == null || "".equals(color)){ color1 = Color.BLACK; }else if("red".equals(color)){ color1 = Color.RED; }else if("green".equals(color)){ color1 = Color.GREEN; }else if("blue".equals(color)){ color1 = Color.BLUE; }else{ color1 = Color.ORANGE; } // 7,Create Simple Styles [Color Fill] Style style = SLD.createSimpleStyle(featureSource.getSchema(),color1); // 8,Show [ shapfile geographic information+Style] Layer layer = new FeatureLayer(featureSource, style); // 9,Add display to map container mapContent.addLayer(layer); return mapContent; } public static void showMap(MapContent mapContent){ JMapFrame.showMap(mapContent); } /** * shp File to Image [Format png] * @param shpFilePath shp Target file * @param destImagePath If not, the converted image is written into the response output stream. * @param response Response flow * @throws Exception */ public static void shp2Image(String shpFilePath,String destImagePath,String color, HttpServletResponse response) throws Exception{ // Stream renderer StreamingRenderer renderer = new StreamingRenderer(); MapContent mapContent = getMapContentByPath(shpFilePath,false,color ); renderer.setMapContent(mapContent); Rectangle imageBounds = new Rectangle(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT); BufferedImage dumpImage = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = dumpImage.createGraphics(); g2d.fillRect(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); renderer.paint(g2d, imageBounds, bounds); g2d.dispose(); if(destImagePath == null || "".equals(destImagePath)){ ImageIO.write(dumpImage, "png", response.getOutputStream()); }else{ ImageIO.write(dumpImage, "png", new File(destImagePath+".png")); } } public static void main(String[] args) throws Exception{ File file = ResourceUtils.getFile("classpath:static/shpTest[Point]/dp_tl.shp"); // from shp Read property information in the file readShpByPath(file.getAbsolutePath(),10); System.out.println("=================Start next shp Write geometric objects in the file==================="); // Create folders first test String filePath = "C:/test/test.shp"; String pointWkt="POINT (120.76164848270959 31.22001141278534)"; Point point = gCreator.createPointByWKT(pointWkt); // Polygon[Noodles] String polygonWkt="POLYGON ((103.859188 34.695908, 103.85661 34.693788, 103.862027 34.69259, 103.863709 34.695078, 103.859188 34.695908))"; Polygon polygon = gCreator.createPolygonByWKT(polygonWkt); // LineString[Line] String linestringWkt="LINESTRING(113.511315990174 41.7274734296674,113.51492087909 41.7284983348307,113.516079593384 41.727649586406,113.515907932007 41.7262243043929,113.514019656861 41.7247989907606,113.512131381714 41.7250872589898,113.51138036319 41.7256637915682,113.511315990174 41.7274734296674)"; LineString lineString = gCreator.createLineByWKT(linestringWkt); // MultiPolygon[Multifaceted String multiPolyWkt = "MULTIPOLYGON(((101.870371 25.19228,101.873633 25.188183,101.880564 25.184416,101.886808 25.186028,101.892043 25.189969,101.896592 25.190163,101.903716 25.190785,101.905454 25.193464,101.899897 25.196202,101.894146 25.197911,101.891657 25.19826,101.886078 25.197658,101.884211145538 25.2007060137013,101.88172564506 25.1949712942389,101.87874 25.199619,101.874641 25.200998,101.868547 25.202415,101.863741 25.202415,101.85887 25.202842,101.854557 25.202182,101.852604 25.199736,101.852282 25.19628,101.854492 25.194183,101.855608 25.192668,101.863698 25.192105,101.870371 25.19228)))"; MultiPolygon multiPolygon = gCreator.createMulPolygonByWKT(multiPolyWkt); // Scope of Geometric Objects [Rectangular Boundary] Envelope envelope = polygon.getEnvelopeInternal(); System.out.println(envelope); // to shp Write geometric objects in the file writeShpByGeom(filePath,point); } }
Contact me
CSDN name: Appleyk
CSDN Blog: https://blog.csdn.net/Appleyk
This CSDN corresponds to blog posts: https://blog.csdn.net/Appleyk/article/details/83376510