记录使用geotools工具,实现shp和geojson数据互转 爬坑:不使用依赖:vividsolutions,因为1。8与geotools20以后版本jts不一致,会报错。com。vividsolutions jtsartifactId 1。8 pom dependency 1。引起pom依赖jarorg。geotools gtshapefileartifactId 20。3 dependency org。geotools gtapiartifactId 20。3 dependency org。geotools gtgeojsonartifactId 20。3 dependency org。geotools gtgeometryartifactId 20。3 dependency org。geotools gtjtswrapperartifactId 20。3 dependency org。geotools gtmainartifactId 20。3 dependency org。geotools gtepsghsqlartifactId 20。3 dependency org。geotools gtopengisartifactId 20。3 dependency org。geotools gtdataartifactId 20。3 dependency org。geotools gtreferencingartifactId 20。3 dependency com。alibaba fastjsonartifactId 1。2。83 dependency dependencies org。apache。maven。plugins mavencompilerpluginartifactId 3。0 1。8source 1。8 true configuration plugin plugins build 2。上代码,自动识别坐标系,默认为84坐标importcom。alibaba。fastjson。JSON; importcom。alibaba。fastjson。JSONArray; importcom。alibaba。fastjson。JSONObject; importorg。geotools。referencing。CRS; importorg。locationtech。jts。geom。; importorg。geotools。data。FeatureWriter; importorg。geotools。data。Transaction; importorg。geotools。data。shapefile。ShapefileDataStore; importorg。geotools。data。shapefile。ShapefileDataStoreFactory; importorg。geotools。data。simple。SimpleFeatureCollection; importorg。geotools。data。simple。SimpleFeatureIterator; importorg。geotools。data。simple。SimpleFeatureSource; importorg。geotools。feature。simple。SimpleFeatureTypeBuilder; importorg。geotools。geojson。feature。FeatureJSON; importorg。geotools。geojson。geom。GeometryJSON; importorg。geotools。referencing。crs。DefaultGeographicCRS; importorg。opengis。feature。simple。SimpleFeature; importorg。opengis。feature。simple。SimpleFeatureType; importorg。opengis。referencing。crs。CoordinateReferenceSystem; importjava。io。; importjava。nio。charset。Charset; importjava。util。; authorqiaobing1226 since20221028上午10:52 参考:https:blog。csdn。netqiaobing1226articledetails127612665 publicclassShp2GeojsonUtils{ privatestaticfinalStringPOINTPoint; privatestaticfinalStringMULTIPOINTMultiPoint; privatestaticfinalStringLINESTRINGLineString; privatestaticfinalStringMULTILINESTRINGMultiLineString; privatestaticfinalStringPOLYGONPolygon; privatestaticfinalStringMULTIPOLYGONMultiPolygon; privatestaticfinalStringTHEGEOMthegeom; privatestaticfinalStringPROPERTIESproperties; privatestaticfinalStringGEOMETRYgeometry; privatestaticfinalStringGBKGBK; geoJson转换为shp文件 paramjsonPath paramshpPath return publicstaticMapString,ObjectgeoJson2Shape(StringjsonPath,StringshpPath){ MapString,ObjectmapnewHashMap(); GeometryJSONgeoJsonnewGeometryJSON(); try{ JSONObjectjsonreadGeoJsonFile(jsonPath); JSONArrayfeatures(JSONArray)json。get(features); JSONObjectfeature0JSONObject。parseObject(features。get(0)。toString()); 获取属性名称 SetpropertiesJSONObject。parseObject(feature0。getString(PROPERTIES))。keySet(); StringstrType((JSONObject)feature0。get(GEOMETRY))。getString(type); StringstrCrsjson。getJSONObject(crs)。getJSONObject(PROPERTIES)。getString(name); CoordinateReferenceSystemcrsCRS。decode(strCrs); ShapefileDataStoreshapefileDataStoredataStore(properties,strType,shpPath,crs); if(shapefileDataStorenull){ returnmap; } 设置Writer FeatureWriterSimpleFeatureType,SimpleFeaturewritershapefileDataStore。getFeatureWriter(shapefileDataStore。getTypeNames()〔0〕, Transaction。AUTOCOMMIT); for(inti0,lenfeatures。size();ilen;i){ StringstrFeaturefeatures。get(i)。toString(); ReaderreadernewStringReader(strFeature); SimpleFeaturefeaturewriter。next(); switch(strType){ casePOINT: feature。setAttribute(THEGEOM,geoJson。readPoint(reader)); break; caseMULTIPOINT: feature。setAttribute(THEGEOM,geoJson。readMultiPoint(reader)); break; caseLINESTRING: feature。setAttribute(THEGEOM,geoJson。readLine(reader)); break; caseMULTILINESTRING: feature。setAttribute(THEGEOM,geoJson。readMultiLine(reader)); break; casePOLYGON: feature。setAttribute(THEGEOM,geoJson。readPolygon(reader)); break; caseMULTIPOLYGON: feature。setAttribute(THEGEOM,geoJson。readMultiPolygon(reader)); break; } Iteratoriteratorproperties。iterator(); while(iterator。hasNext()){ Stringstriterator。next()。toString(); JSONObjectelementJSONObject。parseObject(features。get(i)。toString()); feature。setAttribute(str,JSONObject。parseObject(element。getString(PROPERTIES))。get(str)); } writer。write(); } writer。close(); shapefileDataStore。dispose(); map。put(status,200); map。put(message,shp转换success); }catch(Exceptione){ map。put(status,400); map。put(message,e。getMessage()); e。printStackTrace(); } returnmap; } 读取geojosn文件 paramjsonPath return privatestaticJSONObjectreadGeoJsonFile(StringjsonPath){ 读文件到Stringbuffer StringBuffersbnewStringBuffer(); BufferedReaderbrnull; try{ brnewBufferedReader(newFileReader(jsonPath)); Stringstr; while((strbr。readLine())!null){逐行读取 sb。append(strr); } br。close(); }catch(Exceptione){ if(br!null){ try{ br。close(); }catch(Exceptionexception){ exception。printStackTrace(); } } e。printStackTrace(); } returnJSONObject。parseObject(sb。toString()); } 设置shp文件属性 paramproperties paramstrType paramshpPath return privatestaticShapefileDataStoredataStore(Setproperties,StringstrType,StringshpPath,CoordinateReferenceSystemcrs){ try{ Classlt;?geoTypenull; switch(strType){ casePOINT: geoTypePoint。class; break; caseMULTIPOINT: geoTypeMultiPoint。class; break; caseLINESTRING: geoTypeLineString。class; break; caseMULTILINESTRING: geoTypeMultiLineString。class; break; casePOLYGON: geoTypePolygon。class; break; caseMULTIPOLYGON: geoTypeMultiPolygon。class; break; } 创建shape文件对象 FilefilenewFile(shpPath); MapString,SerializableparamsnewHashMapString,Serializable(); params。put(ShapefileDataStoreFactory。URLP。key,file。toURI()。toURL()); ShapefileDataStoreds(ShapefileDataStore)newShapefileDataStoreFactory()。createNewDataStore(params); 定义图形信息和属性信息 SimpleFeatureTypeBuildertbnewSimpleFeatureTypeBuilder(); 默认84坐标 tb。setCRS(crsnull?DefaultGeographicCRS。WGS84:crs); tb。setName(shapefile); 类型,PointMultiPointLineStringMultiLineStringPolygonMultiPolygon tb。add(thegeom,geoType); IteratorpropertiesIterproperties。iterator(); 设置属性 while(propertiesIter。hasNext()){ StringstrpropertiesIter。next()。toString(); 此处设置为string tb。add(str,String。class); } ds。createSchema(tb。buildFeatureType()); 设置编码 CharsetcharsetCharset。forName(GBK); ds。setCharset(charset); returnds; }catch(Exceptionex){ ex。printStackTrace(); } returnnull; } shp文件转换geojson数据 paramshpPath return publicstaticMapString,Objectshp2Geojson(StringshpPath,StringjsonPath){ MapString,ObjectmapnewHashMap(); 新建json对象 JSONObjectgeojsonObjectnewJSONObject(); geojsonObject。put(type,FeatureCollection); try{ JSONArrayarraynewJSONArray(); StringfileNamereadShpContent(shpPath,array); geojsonObject。put(features,array); geojsonObject。put(name,fileName); StringcrsgetCoordinateSystemWKT(shpPath); GEOGCS表示这个是地址坐标系,PROJCS则表示是平面投影坐标系 JSONObjectcrsJsonnewJSONObject(); JSONObjectproJsonnewJSONObject(); crsJson。put(type,name); if(crs。startsWith(PROJCS)){ proJson。put(name,urn:ogc:def:crs:EPSG::3857); crsJson。put(properties,proJson); }else{ proJson。put(name,urn:ogc:def:crs:OGC:1。3:CRS84); crsJson。put(properties,proJson); } geojsonObject。put(crs,crsJson); itertor。close(); longstartTimeSystem。currentTimeMillis(); 将json字符串使用字符流写入文件 FileoutputfilenewFile(jsonPath); BufferedWriterbufferedWriternewBufferedWriter(newFileWriter(outputfile)); bufferedWriter。write(JSON。toJSONString(geojsonObject)); bufferedWriter。flush(); bufferedWriter。close(); FileoutputfilenewFile(jsonPath); FileOutputStreamfileOutputStreamnewFileOutputStream(outputfile); OutputStreamWriteroutputStreamWriternewOutputStreamWriter(fileOutputStream,utf8); outputStreamWriter。write(JSON。toJSONString(geojsonObject)); outputStreamWriter。flush(); outputStreamWriter。close(); 将json字符串使用字节流写入文件 FileoutputfilenewFile(jsonPath); BufferedOutputStreambufferedOutputStreamnewBufferedOutputStream(newFileOutputStream(outputfile)); byte〔〕bytesJSON。toJSONString(geojsonObject)。getBytes(utf8); bufferedOutputStream。write(bytes); fileOutputStream。write(JSON。toJSONString(geojsonObject)); bufferedOutputStream。flush(); bufferedOutputStream。close(); longendTimeSystem。currentTimeMillis(); System。out。println(当前程序耗时:(endTimestartTime)ms); }catch(Exceptione){ map。put(status,failure); map。put(message,e。getMessage()); e。printStackTrace(); } returngeojsonObject; } privatestaticStringreadShpContent(StringshpPath,JSONArrayarray){ StringfileName; try{ FeatureJSONfjsonnewFeatureJSON(); 获取featurecollection FilefilenewFile(shpPath); ShapefileDataStoreshpDataStorenull; shpDataStorenewShapefileDataStore(file。toURL()); 设置编码 CharsetcharsetCharset。forName(GBK); shpDataStore。setCharset(charset); fileNameshpDataStore。getTypeNames()〔0〕; SimpleFeatureSourcefeatureSourcenull; featureSourceshpDataStore。getFeatureSource(fileName); SimpleFeatureCollectionresultfeatureSource。getFeatures(); SimpleFeatureIteratoritertorresult。features(); 遍历feature转为json对象 while(itertor。hasNext()){ SimpleFeaturefeatureitertor。next(); StringWriterwriternewStringWriter(); fjson。writeFeature(feature,writer); Stringtempwriter。toString(); ObjectgeometryJSONObject。parseObject(temp)。getString(GEOMETRY); byte〔〕btemp。getBytes(iso88591); tempnewString(b,GBK); JSONObjectjsonJSON。parseObject(temp); array。add(json); } itertor。close(); }catch(Exceptione){ e。printStackTrace(); } returnfileName; } 获取Shape文件的坐标系信息,GEOGCS表示这个是地址坐标系,PROJCS则表示是平面投影坐标系 shpPath publicstaticStringgetCoordinateSystemWKT(StringshpPath){ ShapefileDataStoreFactoryfactorynewShapefileDataStoreFactory(); ShapefileDataStoredataStorenull; try{ dataStore(ShapefileDataStore)factory。createDataStore(newFile(shpPath)。toURI()。toURL()); returndataStore。getSchema()。getCoordinateReferenceSystem()。toWKT(); }catch(UnsupportedOperationExceptionIOExceptione){ e。printStackTrace(); }finally{ dataStore。dispose(); } return; } 工具类测试方法 paramargs publicstaticvoidmain(String〔〕args)throwsException{ Shp2GeojsonUtilsshpToGeojsonnewShp2GeojsonUtils(); shape2Geojson StringshpPathUsersecarxDesktopgeojson上下高架mct123ADRoad。shp; StringjsonPathUsersecarxDesktopgeojsonADRoad。geojson; MapString,ObjectmapshpToGeojson。shp2Geojson(shpPath,jsonPath); geojson2Shape StringshpPathUsersecarxDesktopgeojson上下高架mct123ADRoad。shp; StringjsonPathUsersecarxDesktopgeojson上下高架mctADRoad。geojson; MapString,ObjectmapshpToGeojson。geoJson2Shape(jsonPath,shpPath); System。out。println(map。toString()); } } 版权声明:本文为CSDN博主qiaobing1226的原创文章,遵循CC4。0BYSA版权协议,转载请附上原文出处链接及本声明。 原文链接:https:blog。csdn。netqiaobing1226articledetails127612665