geojson文件与shape文件的相互转换
一.geojson转shape
pom文件:
<dependencies><dependency><groupId>nl.cloudfarming.client</groupId><artifactId>lib-geotools</artifactId><version>2.7.5</version></dependency><dependency><groupId>org.geotools</groupId><artifactId>gt-geojson</artifactId><version>18.0</version></dependency><dependency><groupId>com.googlecode.json-simple</groupId><artifactId>json-simple</artifactId><version>1.1.1</version></dependency><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.62</version></dependency></dependencies>
java代码:
import com.alibaba.fastjson.JSONObject;
import com.vividsolutions.jts.geom.*;
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.feature.simple.SimpleFeatureTypeBuilder;
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 java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;public class GeojsonToShape {public static void main(String[] args) {geojson2Shape( "E:\\points.geojson", "E:\\college\\college.shp");}public static void geojson2Shape(String jsonPath, String shpPath){GeometryJSON geojson = new GeometryJSON();try{String geojsonStr = readJson(jsonPath);Map<String, Object> geojsonMap = JSONObject.parseObject(geojsonStr, Map.class);List<Map> features = (List<Map>) geojsonMap.get("features");Map geojsonExemple = features.get(0);String geojsonType = ((Map) geojsonExemple.get("geometry")).get("type").toString();Map<String, Class> mapFields = new HashMap();for (int i = 0; i < features.size(); i++) {Map<String, Object> attributes = (Map<String, Object>) features.get(i).get("properties");for (String key : attributes.keySet()) {Class type = attributes.get(key).getClass();mapFields.put(key, type);}}Class<?> geoType = null;switch(geojsonType){case "Point":geoType = Point.class;break;case "MultiPoint":geoType = MultiPoint.class;break;case "LineString":geoType = LineString.class;break;case "MultiLineString":geoType = MultiLineString.class;break;case "Polygon":geoType = Polygon.class;break;case "MultiPolygon":geoType = MultiPolygon.class;break;}//创建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);for (String key : mapFields.keySet()) {tb.add(key, mapFields.get(key));}ds.createSchema(tb.buildFeatureType());//设置WriterFeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);for(int i=0,len=features.size();i<len;i++){Map oneGeojson = features.get(i);Map<String,Object> attributes = (Map<String, Object>) oneGeojson.get("properties");String strFeature = JSONObject.toJSONString(oneGeojson);Reader reader = new StringReader(strFeature);SimpleFeature feature = writer.next();switch(geojsonType){case "Point":feature.setAttribute("the_geom",geojson.readPoint(reader));break;case "MultiPoint":feature.setAttribute("the_geom",geojson.readMultiPoint(reader));break;case "LineString":feature.setAttribute("the_geom",geojson.readLine(reader));break;case "MultiLineString":feature.setAttribute("the_geom",geojson.readMultiLine(reader));break;case "Polygon":feature.setAttribute("the_geom",geojson.readPolygon(reader));break;case "MultiPolygon":feature.setAttribute("the_geom",geojson.readMultiPolygon(reader));break;}for (String key : attributes.keySet()) {feature.setAttribute(key,attributes.get(key));}writer.write();}writer.close();ds.dispose();}catch(Exception e){System.out.println("转换失败");e.printStackTrace();}}/*** 读取文件* @param filepath 文件路径* @throws IOException*/public static String readJson(String filepath) {FileReader re = null;BufferedReader buff = null;String line = "";try {File file = new File(filepath);re = new FileReader(file);buff = new BufferedReader(re);String tempString = null;while ((tempString = buff.readLine()) != null) {line += tempString;}return line;} catch (Exception e) {System.out.println("失败了");} finally {try {re.close();buff.close();} catch (IOException e) {e.printStackTrace();}}return line;}}
二.shape转geojson
pom:
<dependencies><dependency><groupId>nl.cloudfarming.client</groupId><artifactId>lib-geotools</artifactId><version>2.7.5</version></dependency><dependency><groupId>org.geotools</groupId><artifactId>gt-geojson</artifactId><version>18.0</version></dependency><dependency><groupId>com.googlecode.json-simple</groupId><artifactId>json-simple</artifactId><version>1.1.1</version></dependency><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.62</version></dependency></dependencies>
java代码:
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.geojson.feature.FeatureJSON;
import org.opengis.feature.simple.SimpleFeature;import java.io.*;
import java.nio.charset.Charset;public class ShapeToGeojson {public static void main(String[] args) {shape2Geojson("E:\\jingwei\\china_2000.shp","E:\\points.geojson");}/*** shp转换为Geojson* @param shpPath* @return*/public static void shape2Geojson(String shpPath, String jsonPath){FeatureJSON featureJson = new FeatureJSON();try{BufferedWriter out =new BufferedWriter(new OutputStreamWriter(new FileOutputStream(jsonPath),"UTF-8"));out.write("{\"type\": \"FeatureCollection\",\"features\": [");File file = new File(shpPath);ShapefileDataStore shpDataStore = null;shpDataStore = new ShapefileDataStore(file.toURL());// 设置编码,防止中文乱码shpDataStore.setStringCharset(Charset.forName("gbk"));String typeName = shpDataStore.getTypeNames()[0];SimpleFeatureSource featureSource = null;featureSource = shpDataStore.getFeatureSource (typeName);SimpleFeatureCollection result = featureSource.getFeatures();System.out.println(result.size());SimpleFeatureIterator itertor = result.features();int count = 1;while (itertor.hasNext()) {SimpleFeature feature = itertor.next();StringWriter writer = new StringWriter();featureJson.writeFeature(feature, writer);out.write(writer.toString());System.out.println(count);if (count != result.size() ){out.write( ",");}count ++;}out.write( "]}");itertor.close();out.flush();out.close();}catch(Exception e){System.out.println("转换失败");e.printStackTrace();}}}
geojson文件与shape文件的相互转换相关推荐
- matlab 水平投影,科学网—Matlab中如何将投影信息写入到shape文件中 - 朱永超的博文...
在Matlab中保存shape格式数据时,没有具体的函数可以将投影信息直接写入到shape文件中,不过可以通过另外一种方式实现.看下shape格式的文件不难发现,shape文件的投影信息是一个单独的文 ...
- 导入shape文件到SDE数据库
/** * pDataSet:要导出的数据库的数据集,如果直接导入到数据库而不是数据集,则使用强制转换IWorkspace-->IDataset * strFeatFileDir:要导入的sha ...
- geoserver rest 导入shape文件错误
使用rest接口导入shp文件时出错, java.io.ioexception: current fid index is null, next must be called before write ...
- World Wind Java开发之六——解析shape文件(转)
http://blog.csdn.net/giser_whu/article/details/41647117 最近一直忙于导师项目的事情了,几天没更新了,昨天和今天研究了下WWJ解析shp文件的源代 ...
- 更改shape文件字段名,提示Failed to alter the name of the field
使用ArcMap或ArcCatalog在shape文件上右键--属性--字段,更改字段名字,点击报错或应用提示"Failed to alter the name of the field&q ...
- 有关shape文件的说明
shapefile 是存储地理信息的简单文件格式,但是工作中,常会接到用户的很多问题,这里把常见的汇总下. 一.shape 文件到底可以多大? shapefile 的每个文件都不能超过 2 GB.也就 ...
- 利用arcscene将shape文件拉伸后三维展示
利用arcscene可以将shape文件拉伸三维展示 1. 添加shape文件 2. 拉伸设置,在shp文件属性中选择拉伸并设置,选择合适的比例参数 3. 三维展示效果
- ArcGIS基础知识之shape文件的构成
ArcGIS基础知识之shape文件的构成 一般来说Shape文件主要由3个文件构成: 主文件.索引文件.数据文件.每个shapefile,都至少有这三个文件组成,其中: .shp 存储的是几何要素的 ...
- 解决MapGIS 导出shape文件后属性表内容错乱问题
(1)问题描述 使用MapGIS 6.7 的图形处理-文件转换进行MapGIS文件格式转shape文件是会出现转后mapgis文件属性表乱码问题: 如下图所示,属性表中的内容是错乱的: (2)分析原因 ...
- Python+GDAL面数据中心点提取为单独shape文件,并复制属性数据
最近需要使用GDAL实现shape面数据批量将中心点提取为点shape文件,并复制所有的属性信息.整体的逻辑不是非常复杂,但是在网上现成的代码也找不到. 实现思路 具体思路如下: #mermaid-s ...
最新文章
- 从理论到实践: ORB-SLAM3 Initializer完全解读
- STL源码剖析之算法:lower_bound
- 网站SEO优化介绍搜索引擎给网站排名的过程
- Spring Session - 使用Spring Session从零到一构建分布式session
- Cinder 组件详解 - 每天5分钟玩转 OpenStack(47)
- jQuery对象和DOM对象的区别和转换
- php和app关系,请教一下,app和微信 两个共通的问题
- 给开源项目贡献代码_您可以为开源做出6种非代码贡献
- 套用带标题行的表格样式_比格式刷好用10倍,原来Excel表格还有这么神奇的功能!...
- ft2232驱动安装方法_win7系统无法安装打印机驱动程序的解决方法
- spring boot actuator 如何显示详细信息
- mysql Sql slow log_mysql 5.5 开启慢日志slow log的方法(log_slow_queries)
- 4星|《激荡十年,水大鱼大》:过去十年间国内商业简史
- 失业的程序员(七):梦想和胸襟
- SpringSecurity(安全)
- 老男孩mysql运维dba实战21部完整版_老男孩MySQL高级专业DBA实战课程/高级运维DBA课程/MySQL视频教程 零基础全套...
- mysql 织梦 索引_织梦DedeCMS网站提速优化方案
- BZOJ1930: [Shoi2003]pacman 吃豆豆
- openwrt的luci应用ipk包开发(一)
- 360浏览器总是新建标签页怎么关闭?