geojson读写转换、生成解析(java)

微信搜索:“二十同学” 公众号,欢迎关注一条不一样的成长之路

1.Geotools中Geometry和GeoJson进行相互转换

pom.xml

<geotools.version>17.1</geotools.version>

        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-geojson</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.geotools/gt-main -->
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-main</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-api</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-opengis</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-data</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-referencing</artifactId>
            <version>${geotools.version}</version>
        </dependency>
      
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vividsolutions.jts.geom.*;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import com.vividsolutions.jts.operation.linemerge.LineMerger;
import org.geotools.data.DataUtilities;
import org.geotools.feature.SchemaException;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.geojson.feature.FeatureJSON;
import org.geotools.geojson.geom.GeometryJSON;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.*;

LineString–>geojson


// 由wkt字符串构造LineString对象
WKTReader reader = new WKTReader( geometryFactory );
LineString lineString = (LineString)reader.read("LINESTRING (254058.76074485347 475001.2186020431, 255351.04293761664 474966.9279243938)");
// 设置保留6位小数,否则GeometryJSON默认保留4位小数
GeometryJSON geometryJson = new GeometryJSON(6);
StringWriter writer = new StringWriter();
geometryJson.write(lineString, writer);
System.out.println(writer.toString());
writer.close();

geojson–>LineString

LineString lineString = (LineString) geometryJson.read(new StringReader("{\n" +
                "                \"type\": \"LineString\",\n" +
                "                \"coordinates\": [\n" +
                "                    [\n" +
                "                        120.6584555,\n" +
                "                        30.45144\n" +
                "                    ],\n" +
                "                    [\n" +
                "                        120.1654515,\n" +
                "                        30.54848\n" +
                "                    ]\n" +
                "                ]\n" +
                "            }"));

Feature和FeatureCollection是geotools带属性的,其中FeatureCollection表示Geometry对象集合

LineString转Feature

// geometry是必须的,其他属性可根据需求自定义,但是支持的类型有限,例如这个版本中double是不支持的,只支持float
final SimpleFeatureType TYPE = DataUtilities.createType("Link",
                "geometry:LineString," + // <- the geometry attribute: Point type
                        "gid:String," +   // <- a String attribute
                        "direction:Integer," +   // a number attribute
                        "orientation:Integer"
        );
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
WKTReader reader = new WKTReader( geometryFactory );
FeatureJSON fjson = new FeatureJSON();
LineString lineString = (LineString)reader.read("LINESTRING (254058.76074485347 475001.2186020431, 255351.04293761664 474966.9279243938)");
// 按照TYPE中声明的顺序为属性赋值就可以
featureBuilder.add(lineString);
featureBuilder.add("123456");
featureBuilder.add(2);
featureBuilder.add(0);
SimpleFeature feature = featureBuilder.buildFeature(null);
StringWriter writer = new StringWriter();
fjson.writeFeature(feature, writer);
System.out.println(writer.toString());

执行结果如下:

{“type”:”Feature”,”geometry”:{“type”:”LineString”,”coordinates”:[[254058.7607,475001.2186],[255351.0429,474966.9279]]},”properties”:{“gid”:”123456”,”direction”:2,”orientation”:0},”id”:”fid–5b8f258_15e04bda4b8_-8000”}

LineString转FeatureCollection

String[] WKTS = { "LINESTRING (255351.04293761664 474966.9279243938, 255529.29662365236 474272.4599921228)",
                "LINESTRING (255529.29662365236 474272.4599921228, 256166.05830998957 473979.44920198264)"};
final SimpleFeatureType TYPE = DataUtilities.createType("Link",
                "geometry:LineString," + // <- the geometry attribute: Point type
                        "gid:String," +   // <- a String attribute
                        "direction:Integer," +   // a number attribute
                        "orientation:Integer"
);
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
WKTReader reader = new WKTReader( geometryFactory );
FeatureJSON fjson = new FeatureJSON();
List<SimpleFeature> features = new ArrayList<>();
SimpleFeatureCollection collection = new ListFeatureCollection(TYPE, features);
for (String wkt : WKTS) {
    LineString lineString = (LineString)reader.read(wkt);
    featureBuilder.add(lineString);
    featureBuilder.add("123456");
    featureBuilder.add(2);
    featureBuilder.add(1);
    SimpleFeature feature = featureBuilder.buildFeature(null);
    features.add(feature);
}
StringWriter writer = new StringWriter();
fjson.writeFeatureCollection(collection, writer);
System.out.println(writer.toString());

执行结果如下:

{“type”:”FeatureCollection”,”features”:[{“type”:”Feature”,”geometry”:{“type”:”LineString”,”coordinates”:[[255351.0429,474966.9279],[255529.2966,474272.46]]},”properties”:{“gid”:”123456”,”direction”:2,”orientation”:1},”id”:”fid-67c46b85_15e0778dd81_-8000”},{“type”:”Feature”,”geometry”:{“type”:”LineString”,”coordinates”:[[255529.2966,474272.46],[256166.0583,473979.4492]]},”properties”:{“gid”:”123456”,”direction”:2,”orientation”:1},”id”:”fid-67c46b85_15e0778dd81_-7fff”}]}

如果想point和polygon和LineString都写到一个geojson文件里,geometry类型可以写成geometry,示例如下,将point和polygon放到一起

package com.test.domain.model;

import java.util.Date;

public class GeoModel {

    private String nameId;
    private String geoId;
    private String adminCode;
    private String typeId;
    private String name;
    private String nameEn;
    private String namePy;
    private String createUserId;
    private Date createAt;
    private Date updateAt;
    private String point;
    private String polygon;
    private String area;
    private String taskId;


    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }

    public String getNameId() {
        return nameId;
    }

    public void setNameId(String nameId) {
        this.nameId = nameId;
    }

    public String getGeoId() {
        return geoId;
    }

    public void setGeoId(String geoId) {
        this.geoId = geoId;
    }

    public String getAdminCode() {
        return adminCode;
    }

    public void setAdminCode(String adminCode) {
        this.adminCode = adminCode;
    }

    public String getTypeId() {
        return typeId;
    }

    public void setTypeId(String typeId) {
        this.typeId = typeId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNameEn() {
        return nameEn;
    }

    public void setNameEn(String nameEn) {
        this.nameEn = nameEn;
    }

    public String getNamePy() {
        return namePy;
    }

    public void setNamePy(String namePy) {
        this.namePy = namePy;
    }

    public String getCreateUserId() {
        return createUserId;
    }

    public void setCreateUserId(String createUserId) {
        this.createUserId = createUserId;
    }

    public Date getCreateAt() {
        return createAt;
    }

    public void setCreateAt(Date createAt) {
        this.createAt = createAt;
    }

    public Date getUpdateAt() {
        return updateAt;
    }

    public void setUpdateAt(Date updateAt) {
        this.updateAt = updateAt;
    }

    public String getPoint() {
        return point;
    }

    public void setPoint(String point) {
        this.point = point;
    }

    public String getPolygon() {
        return polygon;
    }

    public void setPolygon(String polygon) {
        this.polygon = polygon;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }



}
    //将属性数据加载到list里
    List<GeoModel> geoModelList = new ArrayList<>();
        
    String writer = creatFeatureCollection(geoModelList);

        writer = writer.replace("{\"type\":\"Feature\"", "\n{\"type\":\"Feature\"");

        String path = "/data/123.geojson";
        File file = new File(path);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            OutputStreamWriter osw=new OutputStreamWriter(fos, "UTF-8");
            BufferedWriter  bw=new BufferedWriter(osw);
            bw.write(writer);
            bw.close();
            osw.close();
            fos.close();

        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException:",e);
        
        } catch (UnsupportedEncodingException e) {
           
            logger.error("UnsupportedEncodingException:",e);

        } catch (IOException e) {
            
            logger.error("IOException:",e);
          
        }
public String creatFeatureCollection(List<GeoModel> geoModels){

        SimpleFeatureType TYPE = null;
        try {
            TYPE = DataUtilities.createType("Link",
                    "geometry:Geometry," +
                            "nameId:String," +
                            "geoId:String," +
                            "adminCode:String," +
                            "typeId:String," +
                            "name:String," +
                            "nameEn:String," +
                            "namePy:String," +
                            "createUserId:String," +
                            "createAt:Date," +
                            "updateAt:Date," +
                            "area:String," +
                            "taskId:String"
            );
        } catch (SchemaException e) {
            logger.error("SchemaException",e);
        }

        SimpleFeatureBuilder featureBuilderPoint = new SimpleFeatureBuilder(TYPE);
        SimpleFeatureBuilder featureBuilderPolygon = new SimpleFeatureBuilder(TYPE);

        WKTReader reader = new WKTReader( autowiredService.getGeometryFactory() );
        GeometryJSON gjson = new GeometryJSON(15);  // 15位小数
        FeatureJSON fjson = new FeatureJSON(gjson);

        List<SimpleFeature> features = new ArrayList<>();
        SimpleFeatureCollection collection = new ListFeatureCollection(TYPE, features);

        for (GeoModel geoModel : geoModels){

            Point point = null;
            try {
                point = (Point)reader.read(geoModel.getPoint());
            } catch (ParseException e) {
                logger.error("ParseException-point:",e);
            }

            featureBuilderPoint.add(point);
            featureBuilderPoint.add(geoModel.getNameId());
            featureBuilderPoint.add(geoModel.getGeoId());
            featureBuilderPoint.add(geoModel.getAdminCode());
            featureBuilderPoint.add(geoModel.getTypeId());
            featureBuilderPoint.add(geoModel.getName());
            featureBuilderPoint.add(geoModel.getNameEn());
            featureBuilderPoint.add(geoModel.getNamePy());
            featureBuilderPoint.add(geoModel.getCreateUserId());
            featureBuilderPoint.add(geoModel.getCreateAt());
            featureBuilderPoint.add(geoModel.getUpdateAt());
            featureBuilderPoint.add(geoModel.getArea());
            featureBuilderPoint.add(geoModel.getTaskId());

            SimpleFeature featurePoint = featureBuilderPoint.buildFeature(null);

            Polygon polygon = null;
            try {
                polygon = (Polygon)reader.read(geoModel.getPolygon());
            } catch (ParseException e) {
                logger.error("ParseException-polygon:",e);
            }

            featureBuilderPolygon.add(polygon);
            featureBuilderPolygon.add(geoModel.getNameId());
            featureBuilderPolygon.add(geoModel.getGeoId());
            featureBuilderPolygon.add(geoModel.getAdminCode());
            featureBuilderPolygon.add(geoModel.getTypeId());
            featureBuilderPolygon.add(geoModel.getName());
            featureBuilderPolygon.add(geoModel.getNameEn());
            featureBuilderPolygon.add(geoModel.getNamePy());
            featureBuilderPolygon.add(geoModel.getCreateUserId());
            featureBuilderPolygon.add(geoModel.getCreateAt());
            featureBuilderPolygon.add(geoModel.getUpdateAt());
            featureBuilderPolygon.add(geoModel.getArea());
            featureBuilderPolygon.add(geoModel.getTaskId());

            SimpleFeature featurePolygon = featureBuilderPolygon.buildFeature(null);

            features.add(featurePoint);
            features.add(featurePolygon);
        }

        StringWriter writer = new StringWriter();

        try {
            fjson.writeFeatureCollection(collection, writer);
        } catch (IOException e) {
            logger.error("writeFeatureCollection异常:",e);
        }

        return writer.toString();

    }

 

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 点我我会动 设计师:白松林 返回首页