小編給大家分享一下MongoDB導(dǎo)入shapefile數(shù)據(jù)的方法,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討方法吧!
成都創(chuàng)新互聯(lián)主要從事成都網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站、網(wǎng)頁(yè)設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)金鳳,十多年網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專業(yè),歡迎來(lái)電咨詢建站服務(wù):18982081108
兩種解決方案:
一、將整個(gè)shapefile轉(zhuǎn)為GeoJSON然后直接導(dǎo)入mongoDB數(shù)據(jù)庫(kù)中
首先,將shapefile數(shù)據(jù)轉(zhuǎn)為WGS84地理坐標(biāo),然后使用GDAL的命令行工具ogr2ogr進(jìn)行格式的轉(zhuǎn)換,轉(zhuǎn)換命令如下:
ogr2ogr -f geoJSON continents.json continents.shp
刪除生成JSON文件的前兩行{ "type": "FeatureCollection",和最后一行}。
最后,使用mongodb的mongoimport工具進(jìn)行導(dǎo)入:
mongoimport --db world --collection continents < continents.json
這樣子整個(gè)shapefile文件在mongodb中是以一個(gè)document存在的。
二、更加細(xì)粒度的存儲(chǔ)方法是將shapefile中的每個(gè)feature取出來(lái)轉(zhuǎn)為GeoJSON存入mongodb
具體實(shí)現(xiàn)代碼入下(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); MongoCollectioncoll = db.getCollection(COLLECTION_NAME); File shapeFile = new File(SHAPE_FILE); FileDataStore store = FileDataStoreFinder.getDataStore(shapeFile); SimpleFeatureSource sfSource = store.getFeatureSource(); SimpleFeatureIterator sfIter = sfSource.getFeatures().features(); // 依次取出每一個(gè)Feature轉(zhuǎn)為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(); } }
看完了這篇文章,相信你對(duì)mongodb導(dǎo)入shapefile數(shù)據(jù)的方法有了一定的了解,想了解更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!