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");
	}
}

---------------------------------------------------------------------------------------------------------------

技术博客

CSDN:http://blog.csdn.NET/gisshixisheng

博客园:http://www.cnblogs.com/lzugis/

在线教程

http://edu.csdn.Net/course/detail/799

Github

https://github.com/lzugis/

联系方式

q       q:1004740957

e-mail:niujp08@qq.com

公众号:lzugis15

Q Q 群:452117357(webgis)

             337469080(Android)



转载于:https://www.cnblogs.com/lzugis/p/7224348.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 GeoTools 库来实现将 SHP 文件发布为 GeoJSON 格式的服务。下面是一个示例代码: ```java import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CoverageStoreInfo; import org.geoserver.catalog.DataStoreInfo; import org.geoserver.catalog.FeatureTypeInfo; import org.geoserver.catalog.NamespaceInfo; import org.geoserver.catalog.StoreInfo; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.impl.CatalogImpl; import org.geoserver.data.util.IOUtils; import org.geoserver.platform.GeoServerExtensions; import org.geoserver.wfs.WFSServiceImpl; import org.geotools.data.DataStore; import org.geotools.data.DataStoreFinder; import org.geotools.data.FeatureSource; import org.geotools.data.FeatureStore; import org.geotools.data.Transaction; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.data.simple.SimpleFeatureStore; import org.geotools.feature.FeatureCollection; import org.geotools.geojson.feature.FeatureJSON; import org.geotools.geometry.jts.ReferencedEnvelope; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.opengis.feature.Property; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.filter.Filter; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("/geojson") public class GeoJSONController { private Catalog catalog; public GeoJSONController() { this.catalog = new CatalogImpl(); } @RequestMapping(value = "/{workspace}/{datastore}/{layer}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> getGeoJSON(@PathVariable("workspace") String workspaceName, @PathVariable("datastore") String datastoreName, @PathVariable("layer") String layerName, HttpServletRequest request) { try { WorkspaceInfo workspace = catalog.getWorkspaceByName(workspaceName); DataStoreInfo dataStore = catalog.getDataStoreByName(datastoreName, workspace); FeatureTypeInfo featureType = catalog.getFeatureTypeByName(workspaceName, layerName); DataStore datastore = DataStoreFinder.getDataStore(dataStore.getConnectionParameters()); SimpleFeatureSource featureSource = datastore.getFeatureSource(featureType.getName()); FeatureCollection<SimpleFeatureType, SimpleFeature> collection = featureSource.getFeatures(); SimpleFeatureCollection features = (SimpleFeatureCollection) collection; // Convert SimpleFeatureCollection to GeoJSON FeatureJSON featureJSON = new FeatureJSON(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); featureJSON.writeFeatureCollection(features, outputStream); return ResponseEntity.ok(outputStream.toString()); } catch (Exception e) { return ResponseEntity.status(500).body("Error: " + e.getMessage()); } } } ``` 在此代码,我们首先获取了指定的工作空间、数据存储和要素类型。然后,我们使用 `DataStoreFinder` 类创建一个 `DataStore` 实例,并从获取要素源。接下来,我们使用 GeoTools 库的 `FeatureJSON` 类将 `SimpleFeatureCollection` 转换GeoJSON 字符串,并返回该字符串作为响应。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值