shapefile geojson格式转换

//shp to geojson

首先拿到SimpleFeatureCollection,然后写入geojson

MapconnectionParams = new HashMap();

connectionParams.put("DriverName", "GeoJSON");

connectionParams.put("DatasourceName", file.getAbsolutePath());

OGRDataStoreFactory factory = new JniOGRDataStoreFactory();

OGRDataStore dataStore = (OGRDataStore)factory.createNewDataStore(connectionParams);

dataStore.createSchema(features, true, null);//核心一句

//shp2json

from osgeoimport gdal

from osgeoimport ogr

def shp2gson():

# 为了支持中文路径,请添加下面这句代码

    gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO")

# 为了使属性表字段支持中文,请添加下面这句

    gdal.SetConfigOption("SHAPE_ENCODING", "")

strVectorFile ="E:\\example.shp"

    # 注册所有的驱动

    ogr.RegisterAll()

# 打开数据

    ds = ogr.Open(strVectorFile, 0)

if ds ==None:

print("打开文件【%s】失败!", strVectorFile)

return

    print("打开文件【%s】成功!", strVectorFile)

driver = ogr.GetDriverByName("GeoJSON")

if driver ==None:

print("打开驱动失败!")

driver.CopyDataSource(ds, "E:\\fibercable.geojson")

if __name__ =='__main__':

shp2gson()

//geojson to shp

直接从geojson中拿到FeatureCollection,剩下的就是怎么写入shp文件

InputStream in = new FileInputStream(geojson);

FeatureJSON fjson = new FeatureJSON(gjson);

SimpleFeatureCollection fc = (SimpleFeatureCollection)fjson.readFeatureCollection(in);

MapParams = new HashMap();

Params.put("DriverName", "ESRI Shapefile");

Params.put("DatasourceName", shpFile.getAbsolutePath());

OGRDataStoreFactory factory2 = new JniOGRDataStoreFactory();

OGRDataStore dataStore2 = (OGRDataStore) factory2.createNewDataStore(Params);

dataStore2.createSchema(fc, true, null);

dataStore2.dispose();


方法二qgis 太简单了,两句话,qgis封装的好,底层也是ogr

layer=QgsVectorLayer(shpfile,'shp','ogr')

err=QW.writeAsVectorFormat(layer,geojsonfile,'utf-8',None,'GeoJSON')

//parse Feature or FeatureCollectionFeaturefeature=(Feature)GeoJSONFactory.create(json);FeatureCollectionfeatureCollection=(FeatureCollection)GeoJSONFactory.create(json);//parse Geometry from FeatureGeoJSONReaderreader=newGeoJSONReader();Geometrygeometry=reader.read(feature.getGeometry());  geometry=reader.read(featureCollection.getFeatures()[0].getGeometry());//create and serialize a FeatureCollectionListfeatures=newArrayList();Mapproperties=newHashMap();  features.add(newFeature(geometry, properties);GeoJSONWriterwriter=newGeoJSONWriter();GeoJSONjson=writer.write(features);

你可能感兴趣的:(shapefile geojson格式转换)