您好,登錄后才能下訂單哦!
小編給大家分享一下mongodb導入shapefile數據的方法,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討方法吧!
兩種解決方案:
一、將整個shapefile轉為GeoJSON然后直接導入mongoDB數據庫中
首先,將shapefile數據轉為WGS84地理坐標,然后使用GDAL的命令行工具ogr2ogr進行格式的轉換,轉換命令如下:
ogr2ogr -f geoJSON continents.json continents.shp
刪除生成JSON文件的前兩行{ "type": "FeatureCollection",和最后一行}。
最后,使用mongodb的mongoimport工具進行導入:
mongoimport --db world --collection continents < continents.json
這樣子整個shapefile文件在mongodb中是以一個document存在的。
二、更加細粒度的存儲方法是將shapefile中的每個feature取出來轉為GeoJSON存入mongodb
具體實現代碼入下(Java版本):
package cn.tzy.mongodb; import java.io.File; import java.io.IOException; import java.io.StringWriter; import org.bson.Document; import org.geotools.data.FileDataStore; import org.geotools.data.FileDataStoreFinder; 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 com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class MongoEx { public static void main(String[] args) throws IOException { final String IP_ADDRESS = "127.0.0.1"; final String DB_NAME = "SpatialFeatures"; final String COLLECTION_NAME = "continents"; final String SHAPE_FILE = "/home/theone/Data/World/continent.shp"; MongoClient client = new MongoClient(IP_ADDRESS, 27017); MongoDatabase db = client.getDatabase(DB_NAME); db.createCollection(COLLECTION_NAME); MongoCollection<Document> coll = db.getCollection(COLLECTION_NAME); File shapeFile = new File(SHAPE_FILE); FileDataStore store = FileDataStoreFinder.getDataStore(shapeFile); SimpleFeatureSource sfSource = store.getFeatureSource(); SimpleFeatureIterator sfIter = sfSource.getFeatures().features(); // 依次取出每一個Feature轉為GeoJSON格式,然后插入到collection中 while (sfIter.hasNext()) { SimpleFeature feature = (SimpleFeature) sfIter.next(); FeatureJSON fjson = new FeatureJSON(); StringWriter writer = new StringWriter(); fjson.writeFeature(feature, writer); String sjson = writer.toString(); Document doc = Document.parse(sjson); coll.insertOne(doc); } client.close(); } }
看完了這篇文章,相信你對mongodb導入shapefile數據的方法有了一定的了解,想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。