GIS開發(fā):mysql空間數(shù)據(jù)導(dǎo)出geojson
使用nodejs,實(shí)現(xiàn)將mysql數(shù)據(jù)庫中的空間數(shù)據(jù)表,導(dǎo)出成geojson的矢量圖層文件,保存。
安裝fs、wellknow和mysql三個(gè)nodejs類庫:
let?fs?=?require("fs");
let?parset?=?require('wellknown');
let?mysql?=?require('mysql');?
//創(chuàng)建mysql的數(shù)據(jù)庫連接
let?connection?=?mysql.createConnection({
?//主機(jī)地址?(
host?????:?'localhost',
//用戶名
user?????:?'root',
//密碼
password?:?'******',
//在mysql中創(chuàng)建的數(shù)據(jù)庫名
database?:?'database'
});
//連接到數(shù)據(jù)庫
connection.connect();
//?var?tabletype;
let?tabledata?=?[];
//查詢空間坐標(biāo)的數(shù)據(jù),并保存
?const?sqlb="select?st_ASTEXT(geometry)?AS?geo?from?dbname";
connection.query(sqlb,?function?(error,?results,?fields)?{
????for(let?k=0;k<results.length;k++){
? ? ??let?tst={};
??????tst?=parset(results[k].geo);
??????tabledata.push(tst);
????}?
});
//查詢空間數(shù)據(jù)表中的其他屬性字段數(shù)據(jù),并保存
let?sql="select?*?from?dbname";
connection.query(sql?,?function?(error,?results,?fields)?{
????let?dataJson??=?results;
? ??let?features=[];
? ??let?name?=[];
? ??let?n?=0;?
????for(let?t?in?dataJson[0]?)?{
????????n++;
????????name[n]?=t;
????}
????//將數(shù)據(jù)庫中的數(shù)據(jù),拼接成geojson的格式
????for(let?i=0;i<dataJson.length;i++){
? ? ? ??let?fdata?=?{};
? ? ? ??let?pdata?=?{};
????????fdata["type"]="Feature";
????????fdata["properties"]?=pdata;
????????for(let?j=1;j<name.length-1;j++){
?????????pdata[name[j]]?=dataJson[i][name[j]];
????????}
????????fdata["geometry"]?=tabledata[i];
????????features.push(fdata);
????}
?//添加geojson的數(shù)據(jù)頭信息
???var?road?=?[]?;
???var?roaddata?={};
???roaddata["type"]?="FeatureCollection";
???roaddata["name"]?="roadcenter";
???roaddata["crs"]?=?{?"type":?"name",?"properties":?{?"name":?"urn:ogc:def:crs:OGC:1.3:CRS84"?}?};
???roaddata["features"]?=features;
???road.push(roaddata);
//保存geojson文件
???var?roadjson?=JSON.stringify(roaddata);
???fs.writeFileSync('filepath',roadjson);
});