geotools中shp和geojson格式的相互转换

概述:

在本文中,讲述如何在geotools中实现shp和geojson数据的相互转换。

效果:

实现代码:

package com.lzugis.geotools;

import java.io.File;
import java.io.Reader;
import java.io.Serializable;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.geotools.data.FeatureWriter;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geojson.feature.FeatureJSON;
import org.geotools.geojson.geom.GeometryJSON;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

import com.amazonaws.util.json.JSONArray;
import com.amazonaws.util.json.JSONObject;
import com.lzugis.CommonMethod;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.MultiLineString;
import com.vividsolutions.jts.geom.MultiPoint;
import com.vividsolutions.jts.geom.MultiPolygon;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;

public class FileFormat {
	private static CommonMethod cm = new CommonMethod();
	/**
	 * geojson转换为shp文件
	 * @param jsonPath
	 * @param shpPath
	 * @return
	 */
	public Map geojson2Shape(String jsonPath, String shpPath){
		Map map = new HashMap();
		GeometryJSON gjson = new GeometryJSON();
		try{
			String strJson = cm.getFileContent(jsonPath);
			JSONObject json = new JSONObject(strJson);
			JSONArray features = (JSONArray) json.get("features");
			JSONObject feature0 = new JSONObject(features.get(0).toString());
			System.out.println(feature0.toString());
			String strType = ((JSONObject)feature0.get("geometry")).getString("type").toString();
			
			Class<?> geoType = null;
			switch(strType){
				case "Point":
					geoType = Point.class;
				case "MultiPoint":
					geoType = MultiPoint.class;
				case "LineString":
					geoType = LineString.class;
				case "MultiLineString":
					geoType = MultiLineString.class;
				case "Polygon":
					geoType = Polygon.class;
				case "MultiPolygon":
					geoType = MultiPolygon.class;
			}
			//创建shape文件对象
			File file = new File(shpPath);
			Map<String, Serializable> params = new HashMap<String, Serializable>();
			params.put( ShapefileDataStoreFactory.URLP.key, file.toURI().toURL() );
			ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);
			//定义图形信息和属性信息
			SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
			tb.setCRS(DefaultGeographicCRS.WGS84);
			tb.setName("shapefile");
			tb.add("the_geom", geoType);
			tb.add("POIID", Long.class);
			ds.createSchema(tb.buildFeatureType());
			//设置编码
            Charset charset = Charset.forName("GBK");
            ds.setCharset(charset);
			//设置Writer
			FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
			
			for(int i=0,len=features.length();i<len;i++){
				String strFeature = features.get(i).toString();
				Reader reader = new StringReader(strFeature);
				SimpleFeature feature = writer.next();
				feature.setAttribute("the_geom",gjson.readMultiPolygon(reader));
				feature.setAttribute("POIID",i);
				writer.write();
			}
			writer.close();
			ds.dispose();
			map.put("status", "success");
			map.put("message", shpPath);
		}
		catch(Exception e){
			map.put("status", "failure");
			map.put("message", e.getMessage());
			e.printStackTrace();
		}
		return map;
	}
	/**
	 * shp转换为Geojson
	 * @param shpPath
	 * @return
	 */
	public Map shape2Geojson(String shpPath, String jsonPath){
		Map map = new HashMap();
		
		FeatureJSON fjson = new FeatureJSON();
		
		try{
			StringBuffer sb = new StringBuffer();
			sb.append("{\"type\": \"FeatureCollection\",\"features\": ");
			
			File file = new File(shpPath);
    		ShapefileDataStore shpDataStore = null;
    		
        	shpDataStore = new ShapefileDataStore(file.toURL());
            //设置编码
            Charset charset = Charset.forName("GBK");
            shpDataStore.setCharset(charset);
            String typeName = shpDataStore.getTypeNames()[0];
            SimpleFeatureSource featureSource = null;
            featureSource =  shpDataStore.getFeatureSource (typeName);
            SimpleFeatureCollection result = featureSource.getFeatures();
            SimpleFeatureIterator itertor = result.features();
            JSONArray array = new JSONArray();
            while (itertor.hasNext())
            {
                SimpleFeature feature = itertor.next();
                StringWriter writer = new StringWriter();
                fjson.writeFeature(feature, writer);
                JSONObject json = new JSONObject(writer.toString());
                array.put(json);
            }
            itertor.close();
            sb.append(array.toString());
            sb.append("}");
            
            //写入文件
            cm.append2File(jsonPath, sb.toString());
            
			map.put("status", "success");
			map.put("message", sb.toString());
		}
		catch(Exception e){
			map.put("status", "failure");
			map.put("message", e.getMessage());
			e.printStackTrace();
			
		}
		return map;
	}
	
	/**
	 * 工具类测试方法
	 * @param args
	 */
	public static void main(String[] args){
		FileFormat fileFormat = new FileFormat();
		long start = System.currentTimeMillis();
		String shpPath = "/Users/lzugis/Documents/chinadata/cityboundry.shp";
		String jsonPath = "/Users/lzugis/Documents/chinadata/cityboundry.geojson";
		Map map = fileFormat.shape2Geojson(shpPath, jsonPath);
		
//		String shpPath = "D:/data/beijing/China43262.shp";
//		String jsonPath = "D:/data/beijing/China4326.geojson";
//		Map map = fileFormat.geojson2Shape(jsonPath, shpPath);
		
		System.out.println(jsonPath+",共耗时"+(System.currentTimeMillis() - start)+"ms");
	}
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏小樱的经验随笔

POJ 2492 A Bug's Life

A Bug's Life Time Limit: 10000MS Memory Limit: 65536K Total Submissions:...

28610
来自专栏函数式编程语言及工具

SDP(9):MongoDB-Scala - data access and modeling

    MongoDB是一种文件型数据库,对数据格式没有硬性要求,所以可以实现灵活多变的数据存储和读取。MongoDB又是一种分布式数据库,与传统关系数据库不同...

3894
来自专栏码匠的流水账

聊聊flink的SourceFunction

flink-streaming-java_2.11-1.6.2-sources.jar!/org/apache/flink/streaming/api/func...

1853
来自专栏扎心了老铁

java优雅的使用elasticsearch api

本文给出一种优雅的拼装elasticsearch查询的方式,可能会使得使用elasticsearch的方式变得优雅起来,使得代码结构很清晰易读。 建立elast...

9517
来自专栏码匠的流水账

聊聊storm的WindowedBolt

storm-2.0.0/storm-client/src/jvm/org/apache/storm/topology/IWindowedBolt.java

752
来自专栏恰同学骚年

数据结构基础温故-1.线性表(下)

在上一篇中,我们了解了单链表与双链表,本次将单链表中终端结点的指针端由空指针改为指向头结点,就使整个单链表形成一个环,这种头尾相接的单链表称为单循环链表,简称循...

992
来自专栏SeanCheney的专栏

《Pandas Cookbook》第09章 合并Pandas对象

1481
来自专栏Android知识点总结

Java总结IO之总集篇

字符流和字节流向来各行其事,很少有交集。 但Reader和Writer有两个奇子,名叫InputStreamReader(男)和OutputStreamWri...

1295
来自专栏技术之路

设计模式:装饰者模式

  装饰者模式么,在生活中我们是经常接触的。比如像我们这么快节奏的生活,好多都是早上去买煎饼。一般我们会这么说:“来一个粗粮煎饼,加两个鸡蛋,加一根肠” 或者:...

2088
来自专栏小樱的经验随笔

BZOJ 1012: [JSOI2008]最大数maxnumber【线段树单点更新求最值,单调队列,多解】

1012: [JSOI2008]最大数maxnumber Time Limit: 3 Sec  Memory Limit: 162 MB Submit: 103...

2946

扫码关注云+社区