服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - java使用GeoTools读取shp文件并画图的操作代码

java使用GeoTools读取shp文件并画图的操作代码

2021-09-23 13:12跟着半仙学java Java教程

GeoTools是ArcGis地图与java对象的桥梁,今天通过本文给大家分享java使用GeoTools读取shp文件并画图,文章通过实例代码给大家介绍的非常详细,需要的朋友参考下吧

GeoTools是ArcGis地图与java对象的桥梁,恰如jdbc之于oracle与java。
shp文件本身是存有地理对象边界坐标、对象中心城市及城市编号的多多边形字符串。
需要使用的依赖如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!-- 添加GeoTools依赖 -->
       <dependency>
           <groupId>org.geotools</groupId>
           <artifactId>gt-shapefile</artifactId>
           <version>${geotools.version}</version>
       </dependency>
 
       <dependency>
           <groupId>org.geotools</groupId>
           <artifactId>gt-swing</artifactId>
           <version>${geotools.version}</version>
       </dependency>
       
       <dependency>
           <groupId>dom4j</groupId>
           <artifactId>dom4j</artifactId>
           <version>1.6.1</version>
       </dependency>
       <dependency>
           <groupId>com.alibaba</groupId>
           <artifactId>fastjson</artifactId>
           <version>1.2.47</version>
       </dependency>

对象:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class CutProperty {
 
    private String province;
    private int x;
    private int y;
 
    /**
     * 图片宽
     * */
    private int width;
 
    /**
     * 图片高
     * */
    private int height;
 
    /**
     * 画图时线条粗细
     * */
    private float weight;
 
    /**
     * 地图坐标右边界
     * */
    private int rightborder;
 
    /**
     * 地图坐标放大倍数
     * */
    private int bei;
 
    /**
     * 文字大小
     * */
    private int stringsize;

来自@author yukun24@126.com的工具类,读取shp文件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.gwhn.geotools;
 
import org.geotools.data.FeatureWriter;
import org.geotools.data.FileDataStoreFactorySpi;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.junit.Test;
import org.locationtech.jts.geom.*;
import org.opengis.feature.Property;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
 
import java.io.File;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.*;
 
public class ShapeUtil {
 
    //读shp文件【几何信息+属性信息】
    public List<Property> SHPRead(String path) throws Exception {
        List<Property> propertyList = new ArrayList<>();
        //基于上面新建的shapfile文件,进行读取
 
        //构建shapefile数据存储的实例
        ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
 
        //基于路径构建文件对象
        File file = new File(path);
 
        //构建一个已存在的shapfile数据源
        //ShapefileDataStore:数据存储实现,允许从Shapefiles读取和写入
        ShapefileDataStore ds = (ShapefileDataStore) dataStoreFactory.createDataStore(file.toURI().toURL());
 
        //设置编码,防止中文读取乱码
        ds.setCharset(Charset.forName("UTF-8"));
 
        //getFeatureSource():ContentFeatureSource
        //这个特性是由 FeatureCollection提供的操作完成的。单独的特征记忆实现由子类提供:
        //SimpleFeatureSource特征资源明确地使用FeatureCollection【集合】,可迭代
        SimpleFeatureSource featureSource = ds.getFeatureSource();
 
        //getFeatures():以FeatureCollection的形式检索所有特性。
        //一个用于处理FeatureCollection的实用工具类。提供一个获取FeatureCollection实例的机制
        FeatureCollection<SimpleFeatureType, SimpleFeature> result = featureSource.getFeatures();
 
        System.out.println("几何对象总共有:" + result.size());
        //features():返回一个FeatureIterator迭代器
        SimpleFeatureIterator it = (SimpleFeatureIterator) result.features();
 
        while (it.hasNext()) {
            SimpleFeature feature = it.next();
            //迭代属性【属性我们可以理解为一个几何对象的属性节点,也就是对一个几何图形的描述字段】
            Iterator<Property> ip = feature.getProperties().iterator();
//            System.out.println("========================");
            //再来个while
            while (ip.hasNext()) {
                Property pro = ip.next();
//                System.out.println(pro.getName()+" = "+pro.getValue());
                propertyList.add(pro);
            }//end 属性迭代
        }
        it.close();
        return propertyList;
    }
   
}

来自@author yukun24@126.com的工具类,此处用来将shp中获取的字符串转化为多多边形对象MultiPolygon

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
package com.gwhn.geotools;
 
 
import org.locationtech.jts.geom.*;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
 
import java.util.List;
 
/**
 * 几何对象构建器
 *
 * @author yukun24@126.com
 * @version V1.0.1
 * @blob http://blog.csdn.net/appleyk
 * @date 2017年12月8日10:38:49
 */
 
//单例模式
public class GeometryCreator {
 
    public static GeometryCreator geometryCreator = null;
 
    private GeometryFactory geometryFactory = new GeometryFactory();
 
    public GeometryCreator() {
    }
 
    /**
     * 返回本类的唯一实例
     *
     * @return
     */
    public static GeometryCreator getInstance() {
        if (geometryCreator == null) {
            return new GeometryCreator();
        }
        return geometryCreator;
    }
 
 
    /**
     * 1.构建点
     */
 
    /**
     * 1.1根据X,Y坐标构建一个几何对象: 点 【Point】
     *
     * @param x
     * @param y
     * @return
     */
    public Point createPoint(double x, double y) {
        Coordinate coord = new Coordinate(x, y);
        Point point = geometryFactory.createPoint(coord);
        return point;
    }
 
    /**
     * 1.2根据几何对象的WKT描述【String】创建几何对象: 点 【Point】
     *
     * @return
     * @throws ParseException
     */
    public Point createPointByWKT(String PointWKT) throws ParseException {
        WKTReader reader = new WKTReader(geometryFactory);
        Point point = (Point) reader.read(PointWKT);
        return point;
    }
 
    /**
     * 1.3根据几何对象的WKT描述【String】创建几何对象:多点 【MultiPoint】
     *
     * @return
     * @throws ParseException
     */
    public MultiPoint createMulPointByWKT(String MPointWKT) throws ParseException {
        WKTReader reader = new WKTReader(geometryFactory);
        MultiPoint mpoint = (MultiPoint) reader.read(MPointWKT);
        return mpoint;
    }
 
 
    /**
     * 2.构建线
     */
 
 
    /**
     * 2.1根据两点 创建几何对象:线 【LineString】
     *
     * @param ax
     * @param ay
     * @param bx
     * @param by
     * @return
     */
    public LineString createLine(double ax, double ay, double bx, double by) {
        Coordinate[] coords = new Coordinate[]{new Coordinate(ax, ay), new Coordinate(bx, by)};
        LineString line = geometryFactory.createLineString(coords);
        return line;
    }
 
    /**
     * 2.2根据线的WKT描述创建几何对象:线 【LineString】
     *
     * @param LineStringWKT
     * @return
     * @throws ParseException
     */
    public LineString createLineByWKT(String LineStringWKT) throws ParseException {
        WKTReader reader = new WKTReader(geometryFactory);
        LineString line = (LineString) reader.read("LINESTRING(0 0, 2 0)");
        return line;
    }
 
    /**
     * 2.3根据点组合的线数组,创建几何对象:多线 【MultiLineString】
     *
     * @param list
     * @return
     */
    public MultiLineString createMLine(List<Coordinate[]> list) {
 
        MultiLineString ms = null;
 
 
        if (list == null) {
            return ms;
        }
 
        LineString[] lineStrings = new LineString[list.size()];
 
 
//      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);   
 
        int i = 0;
        for (Coordinate[] coordinates : list) {
            lineStrings[i] = geometryFactory.createLineString(coordinates);
        }
 
        ms = geometryFactory.createMultiLineString(lineStrings);
 
        return ms;
    }
 
 
    /**
     * 2.4根据几何对象的WKT描述【String】创建几何对象 : 多线【MultiLineString】
     *
     * @param MLineStringWKT
     * @return
     * @throws ParseException
     */
    public MultiLineString createMLineByWKT(String MLineStringWKT) throws ParseException {
        WKTReader reader = new WKTReader(geometryFactory);
        MultiLineString line = (MultiLineString) reader.read(MLineStringWKT);
        return line;
    }
 
 
    /**
     * 3.构建多边形
     */
 
 
    /**
     * 3.1 根据几何对象的WKT描述【String】创建几何对象:多边形 【Polygon】
     *
     * @param PolygonWKT
     * @return
     * @throws ParseException
     */
    public Polygon createPolygonByWKT(String PolygonWKT) throws ParseException {
        WKTReader reader = new WKTReader(geometryFactory);
        Polygon polygon = (Polygon) reader.read(PolygonWKT);
        return polygon;
    }
 
    /**
     * 3.2 根据几何对象的WKT描述【String】创建几何对象: 多多边形 【MultiPolygon】
     *
     * @param MPolygonWKT
     * @return
     * @throws ParseException
     */
    public MultiPolygon createMulPolygonByWKT(String MPolygonWKT) throws ParseException {
        WKTReader reader = new WKTReader(geometryFactory);
        MultiPolygon mpolygon = (MultiPolygon) reader.read(MPolygonWKT);
        return mpolygon;
    }
 
    /**
     * 根据多边形数组 进行多多边形的创建
     *
     * @param polygons
     * @return
     * @throws ParseException
     */
    public MultiPolygon createMulPolygonByPolygon(Polygon[] polygons) throws ParseException {
 
        return geometryFactory.createMultiPolygon(polygons);
    }
 
    /**
     * 4.构建几何对象集合
     */
 
 
    /**
     * 4.1 根据几何对象数组,创建几何对象集合:【GeometryCollection】
     *
     * @return
     * @throws ParseException
     */
    public GeometryCollection createGeoCollect(Geometry[] geoArray) throws ParseException {
//            LineString line = createLine(125.12,25.4,85.63,99.99);   
//            Polygon poly    =  createPolygonByWKT("POLYGON((20 10, 30 0, 40 10, 30 20, 20 10))");   
//            Geometry g1     = geometryFactory.createGeometry(line);   
//            Geometry g2     = geometryFactory.createGeometry(poly);   
//            Geometry[] geoArray = new Geometry[]{g1,g2};   
        GeometryCollection gc = geometryFactory.createGeometryCollection(geoArray);
        return gc;
    }
 
 
    /**
     * 5.构建圆
     */
 
    /**
     * 5.1 根据圆点以及半径创建几何对象:特殊的多边形--圆 【Polygon】
     *
     * @param x
     * @param y
     * @param RADIUS
     * @return
     */
    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;
    }
 
 
    /**
     *  6.构建环
     */
 
    /**
     * 6.1 根据WKT创建环
     *
     * @param ringWKT
     * @return
     * @throws ParseException
     */
    public LinearRing createLinearRingByWKT(String ringWKT) throws ParseException {
        WKTReader reader = new WKTReader(geometryFactory);
        LinearRing ring = (LinearRing) reader.read(ringWKT);
        return ring;
    }
 
}

有xml如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<application>
    <!-- 网络配置-->
    <module name="Http">
 
        <group name="FileExport">
            <configValue key="ShapePath">D:/testspace/spd/rain/</configValue>
            <configValue key="ProvinceShapePath">D:/testspace/spd/Provinces_shp/</configValue>
            <configValue key="ProvincePath">D:\testspace\spd\output\</configValue>
            <configValue key="ExportPath">D:\testspace\spd\Export\</configValue>
            <configValue key="PropertyPath">D:\testspace\spd\Export\</configValue>
        </group>
        
    </module>
</application>

xml读取以获取shp文件位置和图片输出位置:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.gwhn.Util;
 
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Text;
import org.dom4j.io.SAXReader;
 
import java.io.File;
import java.util.Iterator;
 
/**
 * @author banxian
 * @date 2021/1/21 15:56
 */
public class YereeXmlContext {
 
    /**
     * 根据一二三级字节点的key,迭代到第三级节点根据三级key获取值
     * <!-- 网络配置-->
     * <module name="Http">
     *    <group name="FileUpload">
     *        <configValue key="TempDir">D:\\temp\\upload\\</configValue>
     *    </group>
     * </module>
     *
     * @param key1
     * @param key2
     * @param key3
     * @return
     * @author banxian
     * @date: 2021/1/21 19:51
     */
    public String getXmlValue(String key1, String key2, String key3) {
        try {
            //1.创建Reader对象
            SAXReader reader = new SAXReader();
            //2.加载xml
            String directoryPath = Thread.currentThread().getContextClassLoader().getResource("config.xml").getPath();//获取项目根目录
            Document document = reader.read(new File(directoryPath));
            //3.获取根节点
            Element rootElement = document.getRootElement();
            Element moduleElement = getTargetElement(key1, rootElement);
            Element groupElement = getTargetElement(key2, moduleElement);
            Element configElement = getTargetElement(key3, groupElement);
            Attribute attribute = (Attribute) configElement.attributes().get(0);
            String key = attribute.getValue();
            Text text3 = (Text) configElement.content().get(0);
            String value = text3.getText();
            return value;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * 获取和targetKey匹配的一个子节点
     *
     * @param targetKey
     * @param parentElement
     * @return
     * @author banxian
     * @date: 2021/1/21 19:53
     */
    public Element getTargetElement(String targetKey, Element parentElement) {
        Iterator iterator = parentElement.elementIterator();
        Element childElement = null;
        while (iterator.hasNext()) {
            Element element = (Element) iterator.next();
            Attribute attribute = (Attribute) element.attributes().get(0);
            String key = attribute.getValue();
            if (key.equals(targetKey) || key == targetKey) {
                childElement = element;
                break;
            }
        }
        return childElement;
    }
}

核心类:用多边形绘图

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package com.gwhn.Util;
 
import com.gwhn.entity.CutProperty;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.MultiPolygon;
 
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.List;
 
/**
 * @author banxian
 * @date 2021/6/28 12:37
 */
public class PolygonUtil {
 
    ImageUtils imageUtils = new ImageUtils();
    TxtUtil txtUtil = new TxtUtil();
 
    /**
     * 根据多多边形画图
     * @param path
     * @param cutProperty
     * @param multiPolygonList
     * @return
     * @author banxian
     * @date: 2021/6/30 15:31
     */
    public void graphicsByMultiPolygon(String path, List<MultiPolygon> multiPolygonList, CutProperty cutProperty) {
        try {
            int imageWidth = cutProperty.getWidth();// 图片的宽度
            int imageHeight = cutProperty.getHeight();// 图片的高度
            BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = (Graphics2D) image.getGraphics();
            graphics.setColor(Color.white);
            graphics.fillRect(0, 0, imageWidth, imageHeight);
            graphics.setColor(Color.black);
            int m = cutProperty.getBei() / 100;
            graphics.setStroke(new BasicStroke(cutProperty.getWeight() * m));//线条粗细
            Font font = new Font("宋体", Font.BOLD, 1200);
            graphics.setFont(font);
            graphics.drawString(cutProperty.getProvince(),  12500, 1500);
            for (MultiPolygon multiPolygon : multiPolygonList) {
                int num = multiPolygon.getNumGeometries();
                for (int i = 0; i < num; i++) {
                    Geometry geometry = multiPolygon.getGeometryN(i);
                    drawPolygon(geometry, cutProperty, graphics);
                }
            }
            imageUtils.createImage(path, image);
            System.out.println(path + ":" + font.getSize());
        } catch (
                Exception e) {
            e.printStackTrace();
        }
 
    }
 
    /**
     * 画出一个多边形
     * @param geometry
     * @param cutProperty
     * @param graphics2D
     * @return
     * @author banxian
     * @date: 2021/6/28 12:37
     */
    public void drawPolygon(Geometry geometry, CutProperty cutProperty, Graphics2D graphics2D) {
        int m = cutProperty.getBei() / 100;
        Double xtemp = Double.valueOf(cutProperty.getX() * m);
        Double ytemp = Double.valueOf(cutProperty.getY() * m);
 
        //处理飞地
        if (geometry.toString().contains("),")) {
            String geoStr = geometry.toString();
            String tempStr = geoStr.substring(9, geoStr.length() - 1) + ",";
            while (tempStr.contains("),")) {
                String temp = tempStr.substring(0, tempStr.indexOf("),") + 2);
                tempStr = tempStr.substring(temp.length()).trim();
                Polygon polygon = txtUtil.getPolygonByStr(temp,cutProperty);
                graphics2D.drawPolygon(polygon);
            }
        } else {
            Coordinate[] coordinates = geometry.getCoordinates();
            Polygon polygon = new Polygon();
            Double x, y;
            for (int j = 0; j < coordinates.length; j++) {
                Coordinate coordinate = coordinates[j];
                x = coordinate.getX() * cutProperty.getBei() - xtemp;
                y = cutProperty.getRightborder() * m - coordinate.getY() * cutProperty.getBei() - ytemp;
                polygon.addPoint(x.intValue(), y.intValue());
            }
            graphics2D.drawPolygon(polygon);
        }
    }
}

工具类:处理特殊的边界,一般由飞地、岛屿组成

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package com.gwhn.Util;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gwhn.entity.CutProperty;
 
import java.awt.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * @author banxian
 * @date 2021/5/10 15:57
 */
public class TxtUtil {
 
    public Polygon getPolygonByStr(String polygonStr,CutProperty cutProperty) {
        polygonStr = polygonStr.substring(1, polygonStr.length() - 2) + ",";
        List<String> polygonStrList = new ArrayList<>();
        while (polygonStr.contains(",")) {
            String pointStr = polygonStr.substring(0, polygonStr.indexOf(",")).trim();
            polygonStrList.add(pointStr);
            polygonStr = polygonStr.substring(polygonStr.indexOf(",") + 1);
        }
        return transPointStrToPolygon(polygonStrList, cutProperty);
    }
 
    public Polygon transPointStrToPolygon(List<String> polygonStrList,CutProperty cutProperty) {
        int m = cutProperty.getBei() / 100;
        Double xtemp = Double.valueOf(cutProperty.getX() * m);
        Double ytemp = Double.valueOf(cutProperty.getY() * m);
        Polygon polygon = new Polygon();
        for (String pointStr : polygonStrList) {
            Double x = Double.parseDouble(pointStr.substring(0, pointStr.indexOf(" ")));
            Double y = Double.parseDouble(pointStr.substring(pointStr.indexOf(" ")).trim());
            x = x * cutProperty.getBei() - xtemp;
            y = cutProperty.getRightborder()*m - y * cutProperty.getBei()-ytemp;
            polygon.addPoint(x.intValue(), y.intValue());
        }
        return polygon;
    }
 
    //读取json文件
    public String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
 
    /**
     * 读取json获取图片剪切参数
     *
     * @param
     * @return
     * @author banxian
     * @date: 2021/6/25 8:16
     */
    public Map<String, CutProperty> getCutPropertyMap() {
        String path = Thread.currentThread().getContextClassLoader().getResource("property.json").getPath();//获取项目根目录
        String s = readJsonFile(path);
        JSONObject jsonObject = JSON.parseObject(s);
        JSONArray jsonArray = jsonObject.getJSONArray("properties");//构建JSONArray数组
        List<CutProperty> cutPropertyList = jsonArray.toJavaList(CutProperty.class);
        Map<String, CutProperty> cutPropertyMap = new HashMap();
        for (CutProperty cutProperty : cutPropertyList) {
            cutPropertyMap.put(cutProperty.getProvince(), cutProperty);
        }
        return cutPropertyMap;
    }
    
}

核心类:从读到的shp文件数据中提取字符串转化为多多边形,绘图

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package com.gwhn.controller;
 
import com.gwhn.Util.PolygonUtil;
import com.gwhn.Util.TxtUtil;
import com.gwhn.Util.YereeXmlContext;
import com.gwhn.entity.CutProperty;
import com.gwhn.geotools.GeometryCreator;
import com.gwhn.geotools.ShapeUtil;
import org.locationtech.jts.geom.MultiPolygon;
import org.opengis.feature.Property;
 
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
/**
 * @author banxian
 * @date 2021/6/1 8:12
 */
public class ShpPictureController {
    PolygonUtil polygonUtil = new PolygonUtil();
    TxtUtil txtUtil = new TxtUtil();
    Map<String, CutProperty> cutPropertyMap = txtUtil.getCutPropertyMap();
 
    /**
     * 根据国家shp文件画出中国地图
     * @param
     * @return
     * @author banxian
     * @date: 2021/6/28 12:35
     */
    public void doNation() {
        YereeXmlContext yereeXmlContext = new YereeXmlContext();
        GeometryCreator geometryCreator = new GeometryCreator();
        String shapePath = yereeXmlContext.getXmlValue("Http", "FileExport", "ProvincePath") + "province.shp";
        ShapeUtil shapeUtil = new ShapeUtil();
        try {
            List<Property> propertyList = shapeUtil.SHPRead(shapePath);
            List<MultiPolygon> multiPolygonList = new ArrayList<>();
            for (int i = 0; i * 8 < propertyList.size(); i++) {
                Property property = propertyList.get(i * 8);
                String valueStr = property.getValue().toString();
                MultiPolygon multiPolygon = geometryCreator.createMulPolygonByWKT(valueStr);
                multiPolygonList.add(multiPolygon);
            }
            String path = yereeXmlContext.getXmlValue("Http", "FileExport", "ExportPath");
            File newFileDir = new File(path);
            //如果不存在 则创建
            if (!newFileDir.exists()) {
                newFileDir.mkdirs();
            }
//            String picturName = imageUtils.genImageName() + ".jpg";
            String picturName = "中国.jpg";
            CutProperty cutProperty = cutPropertyMap.get("中国");
            polygonUtil.graphicsByMultiPolygon(path + picturName, multiPolygonList, cutProperty);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("完成");
    }
 
    /**
     * 根据分省shp文件画出地图
     * @param
     * @return
     * @author banxian
     * @date: 2021/6/28 12:35
     */
    public void doProvince() {
        YereeXmlContext yereeXmlContext = new YereeXmlContext();
        GeometryCreator geometryCreator = new GeometryCreator();
        ShapeUtil shapeUtil = new ShapeUtil();
        String shapeDirPath = yereeXmlContext.getXmlValue("Http", "FileExport", "ProvinceShapePath");
 
        List<File> fileList = new ArrayList<>();
        fileList = getFileList(shapeDirPath, fileList);
        for (int j = 0; j < fileList.size(); j++) {
            File file = fileList.get(j);
            if (file.getName().contains(".shp")) {
                File parentFile = file.getParentFile();
                String province = parentFile.getName();
                System.out.println(province);
                int size = 7;
                if (province.equals("湖北") || province == "湖北" || province.equals("安徽") || province == "安徽") {
                    size = 10;
                }
                CutProperty cutProperty = cutPropertyMap.get(province);
                try {
                    List<Property> propertyList = shapeUtil.SHPRead(file.getPath());
                    List<MultiPolygon> multiPolygonList = new ArrayList<>();
                    for (int i = 0; i * size < propertyList.size(); i++) {
                        String valueStr = propertyList.get(i * size).getValue().toString();
                        MultiPolygon multiPolygon = geometryCreator.createMulPolygonByWKT(valueStr);
                        multiPolygonList.add(multiPolygon);
                    }
                    String path = yereeXmlContext.getXmlValue("Http", "FileExport", "ExportPath");
                    ;
                    File newFileDir = new File(path);
                    //如果不存在 则创建
                    if (!newFileDir.exists()) {
                        newFileDir.mkdirs();
                    }
                    String picturName = province + ".jpg";
                    polygonUtil.graphicsByMultiPolygon(path + picturName, multiPolygonList, cutProperty);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("完成");
    }
 
    /**
     * 获取shp文件集合
     * @param dirPath
     * @param fileList
     * @return
     * @author banxian
     * @date: 2021/6/28 12:36
     */
    public List<File> getFileList(String dirPath, List<File> fileList) {
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        for (File file : dir.listFiles()) {
            if (!file.isDirectory()) {
                fileList.add(file);
            } else {
                getFileList(file.getPath(), fileList);
            }
        }
        return fileList;
    }
 
}

地图坐标截取参数

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
{
  "properties": [
    {
      "province": "中国",
      "x": 8000,
      "y": 18600,
      "width": 25000,
      "height": 15000,
      "weight": 5.0,
      "bei":350,
      "rightborder": 25000,
      "stringsize": 500
    },
    {
      "province": "上海",
      "x": 12050,
      "y": 21800,
      "width": 23000,
      "height": 16000,
      "weight": 0.8,
      "bei": 10000,
      "rightborder": 25000,
      "stringsize": 500
    },
    {
      "province": "云南",
      "x": 9700,
      "y": 22000,
      "width": 25000,
      "height": 25000,
      "weight": 2.0,
      "bei": 2500,
      "rightborder": 25000,
      "stringsize": 50
    },
    {
      "province": "内蒙古",
      "x": 9000,
      "y": 19000,
      "width": 25000,
      "height": 15000,
      "weight": 3.0,
      "bei": 600,
      "rightborder": 25000,
      "stringsize": 180
    },
    {
      "province": "北京",
      "x": 11515,
      "y": 20830,
      "width": 25000,
      "height": 25000,
      "weight": 1.0,
      "bei": 10000,
      "rightborder": 25000,
      "stringsize": 600
    },
    {
      "province": "吉林",
      "x": 12100,
      "y": 20200,
      "width": 25000,
      "height": 17000,
      "weight": 2.0,
      "bei": 2100,
      "rightborder": 25000,
      "stringsize": 40
    },
    {
      "province": "四川",
      "x": 9600,
      "y": 21500,
      "width": 25000,
      "height": 20000,
      "weight": 2.0,
      "bei": 1900,
      "rightborder": 25000,
      "stringsize": 40
    },
    {
      "province": "天津",
      "x": 11600,
      "y": 20920,
      "width": 25000,
      "height": 25000,
      "weight": 1.0,
      "bei": 10000,
      "rightborder": 25000,
      "stringsize": 600
    },
    {
      "province": "宁夏",
      "x": 10400,
      "y": 20960,
      "width": 20000,
      "height": 25000,
      "weight": 1.0,
      "bei": 4210,
      "rightborder": 25000,
      "stringsize": 40
    },
    {
      "province": "安徽",
      "x": 11350,
      "y": 21500,
      "width": 25000,
      "height": 22000,
      "weight": 1.0,
      "bei": 3300,
      "rightborder": 25000,
      "stringsize": 25
    },
    {
      "province": "山东",
      "x": 11430,
      "y": 21050,
      "width": 25000,
      "height": 20000,
      "weight": 1.0,
      "bei": 2900,
      "rightborder": 25000,
      "stringsize": 35
    },
    {
      "province": "山西",
      "x": 10900,
      "y": 20850,
      "width": 25000,
      "height": 25000,
      "weight": 1.0,
      "bei": 3500,
      "rightborder": 25000,
      "stringsize": 25
    },
    {
      "province": "广东",
      "x": 10750,
      "y": 22400,
      "width": 25000,
      "height": 15000,
      "weight": 1.0,
      "bei": 2200,
      "rightborder": 25000,
      "stringsize": 40
    },
    {
      "province": "广西",
      "x": 10400,
      "y": 22200,
      "width": 25000,
      "height": 18000,
      "weight": 1.0,
      "bei": 2600,
      "rightborder": 25000,
      "stringsize": 35
    },
    {
      "province": "新疆",
      "x": 7200,
      "y": 19800,
      "width": 25000,
      "height": 20000,
      "weight": 2.0,
      "bei": 900,
      "rightborder": 25000,
      "stringsize": 150
    },
    {
      "province": "江苏",
      "x": 11550,
      "y": 21400,
      "width": 25000,
      "height": 25000,
      "weight": 1.0,
      "bei": 4000,
      "rightborder": 25000,
      "stringsize": 25
    },
    {
      "province": "江西",
      "x": 11250,
      "y": 21950,
      "width": 25000,
      "height": 25000,
      "weight": 1.0,
      "bei": 4000,
      "rightborder": 25000,
      "stringsize": 25
    },
    {
      "province": "河北",
      "x": 11250,
      "y": 20600,
      "width": 25000,
      "height": 25000,
      "weight": 1.0,
      "bei": 3000,
      "rightborder": 25000,
      "stringsize": 40
    },
    {
      "province": "河南",
      "x": 10900,
      "y": 21200,
      "width": 25000,
      "height": 23000,
      "weight": 1.0,
      "bei": 2700,
      "rightborder": 25000,
      "stringsize": 25
    },
    {
      "province": "浙江",
      "x": 11800,
      "y": 21800,
      "width": 25000,
      "height": 25000,
      "weight": 1.0,
      "bei": 5000,
      "rightborder": 25000,
      "stringsize": 25
    },
    {
      "province": "湖北",
      "x": 10800,
      "y": 21500,
      "width": 25000,
      "height": 20000,
      "weight": 1.0,
      "bei": 3000,
      "rightborder": 25000,
      "stringsize": 30
    },
    {
      "province": "湖南",
      "x": 10800,
      "y": 21900,
      "width": 25000,
      "height": 25000,
      "weight": 1.0,
      "bei": 3500,
      "rightborder": 25000,
      "stringsize": 25
    },
    {
      "province": "甘肃",
      "x": 9000,
      "y": 20300,
      "width": 25000,
      "height": 25000,
      "weight": 2.0,
      "bei": 1200,
      "rightborder": 25000,
      "stringsize": 70
    },
    {
      "province": "福建",
      "x": 11550,
      "y": 22050,
      "width": 25000,
      "height": 25000,
      "weight": 1.0,
      "bei": 4000,
      "rightborder": 25000,
      "stringsize": 25
    },
    {
      "province": "西藏",
      "x": 7500,
      "y": 21000,
      "width": 25000,
      "height": 15000,
      "weight": 1.5,
      "bei": 1000,
      "rightborder": 25000,
      "stringsize": 100
    },
    {
      "province": "贵州",
      "x": 10350,
      "y": 21900,
      "width": 25000,
      "height": 25000,
      "weight": 1.0,
      "bei": 3200,
      "rightborder": 25000,
      "stringsize": 35
    },
    {
      "province": "辽宁",
      "x": 11850,
      "y": 20500,
      "width": 25000,
      "height": 25000,
      "weight": 1.0,
      "bei": 3300,
      "rightborder": 25000,
      "stringsize": 25
    },
    {
      "province": "重庆",
      "x": 10500,
      "y": 21700,
      "width": 25000,
      "height": 25000,
      "weight": 1.0,
      "bei": 4700,
      "rightborder": 25000,
      "stringsize": 20
    },
    {
      "province": "陕西",
      "x": 10450,
      "y": 21000,
      "width": 25000,
      "height": 25000,
      "weight": 1.0,
      "bei": 2900,
      "rightborder": 25000,
      "stringsize": 25
    },
    {
      "province": "青海",
      "x": 8700,
      "y": 20900,
      "width": 25000,
      "height": 15000,
      "weight": 2.0,
      "bei": 1500,
      "rightborder": 25000,
      "stringsize": 70
    },
    {
      "province": "黑龙江",
      "x": 12000,
      "y": 19500,
      "width": 25000,
      "height": 18000,
      "weight": 1.0,
      "bei": 1500,
      "rightborder": 25000,
      "stringsize": 60
    }
  ]
}

测试类

?
1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
        try {
            ShpPictureController shpPictureController = new ShpPictureController();
//            shpPictureController.doProvince();
            shpPictureController.doNation();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

最终画出的图片效果如下:

java使用GeoTools读取shp文件并画图的操作代码

到此这篇关于java使用GeoTools读取shp文件并画图的操作代码的文章就介绍到这了,更多相关java读取shp文件并画图内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/oLengYueHun/article/details/118378393

延伸 · 阅读

精彩推荐
  • Java教程小米推送Java代码

    小米推送Java代码

    今天小编就为大家分享一篇关于小米推送Java代码,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧...

    富贵稳中求8032021-07-12
  • Java教程20个非常实用的Java程序代码片段

    20个非常实用的Java程序代码片段

    这篇文章主要为大家分享了20个非常实用的Java程序片段,对java开发项目有所帮助,感兴趣的小伙伴们可以参考一下 ...

    lijiao5352020-04-06
  • Java教程xml与Java对象的转换详解

    xml与Java对象的转换详解

    这篇文章主要介绍了xml与Java对象的转换详解的相关资料,需要的朋友可以参考下...

    Java教程网2942020-09-17
  • Java教程Java使用SAX解析xml的示例

    Java使用SAX解析xml的示例

    这篇文章主要介绍了Java使用SAX解析xml的示例,帮助大家更好的理解和学习使用Java,感兴趣的朋友可以了解下...

    大行者10067412021-08-30
  • Java教程Java BufferWriter写文件写不进去或缺失数据的解决

    Java BufferWriter写文件写不进去或缺失数据的解决

    这篇文章主要介绍了Java BufferWriter写文件写不进去或缺失数据的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望...

    spcoder14552021-10-18
  • Java教程升级IDEA后Lombok不能使用的解决方法

    升级IDEA后Lombok不能使用的解决方法

    最近看到提示IDEA提示升级,寻思已经有好久没有升过级了。升级完毕重启之后,突然发现好多错误,本文就来介绍一下如何解决,感兴趣的可以了解一下...

    程序猿DD9332021-10-08
  • Java教程Java实现抢红包功能

    Java实现抢红包功能

    这篇文章主要为大家详细介绍了Java实现抢红包功能,采用多线程模拟多人同时抢红包,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙...

    littleschemer13532021-05-16
  • Java教程Java8中Stream使用的一个注意事项

    Java8中Stream使用的一个注意事项

    最近在工作中发现了对于集合操作转换的神器,java8新特性 stream,但在使用中遇到了一个非常重要的注意点,所以这篇文章主要给大家介绍了关于Java8中S...

    阿杜7472021-02-04