使用node.js将postgres库中的空间数据导出为geojson

如果能使用node.js直接将postgres的空间数据导出为geojson,然后再使用tippecanoe进行切片,对于前端地图开发人员将会方便不少。

第一步

先看一下geojson的格式,如下:

 1 { 2 "type": "FeatureCollection", 3 "name": "geodata1", 4 "features": [ 5  { 6 "type": "Feature", 7 "properties": { 8 "name": "name1", 9 "type": 110  },11 "geometry": {12 "type": "LineString", "coordinates": [[1.1, 1.2], [1.5, 1.3], [1.7, 1.4], [1.8, 1.2]]13  }14  }15  ]16 }

一个空间数据可导出为一个geojson文件:

1.表名可以对于geojson中对象的name,

2.表中的一行数据生成一个feature,即features数组的一个元素

3.字段对应于feature的properties

4.geometry就是空间字段转换后的结果

    如下,geom是空间字段,使用st_asgeojosn将geom字段转为geojson     

1 // 查询sql2 select st_asgeojson(geom) as geometry from "position";3 // 结果4 {"type":"Point","coordinates":[116.789962214781,41.28758603506076]}

第二步

了解geojson的格式后,其实就比较简单了:

1.查询数据,表名为table1,字段为: 必要的属性如name,转换的geojson

1 select name, st_asgeojson(geom) as geometry from "position";

2.将查询结果制作成一个个的feature对象,放入数组features中,如下

 1 var features = [ 2  { 3 "type": "Feature", 4 "properties": { 5 "name": 1 6  }, 7 "geometry": { 8 "type": "Point", "coordinates": [[1,1]] 9  }10  },11  {12 "type": "Feature",13 "properties": {14 "name": 215  },16 "geometry": {17 "type": "Point", "coordinates": [[1, 2]]18  }19  }20 ]

3.将表名和features信息填入一个geojson对象中:

1 var geojson = {2 "type": "FeatureCollection",3 "name": table1,4 "features": features5 }

最后将geojson写入文件即可。

 主要代码如下:

 1 var fs = require(‘fs‘) 2 let config = require(‘./config‘) 3 let sql = require(‘./src/sql‘) 4 let conStr = config.conStr 5 let selectStr = require(‘./src/selectStr‘).selectStr 6  7 selectStr.forEach(item => { 8  sql.init(conStr) 9 sql.select(item.selectStr, function (result) {10 console.info(item.name + ‘ start...‘)11 let features = []12 result.rows.forEach(obj => {13 let feature = {14 "type": "Feature",15 "properties": {16 // 属性都放在这17  },18 "geometry": JSON.parse(obj.geometry)19  }20 // 挂接属性21 for (let key in obj) {22 if (obj.hasOwnProperty(key) && key != ‘geometry‘) {23 // console.log(key)24 // console.log(obj[key] + ‘‘)25 feature.properties[key] = obj[key] + ‘‘26  }27  }28  features.push(feature)29  })30 let geojson = {31 "type": "FeatureCollection",32 "name": item.name,33 "features": features34  }35 fs.writeFile(‘./result/‘ + item.name + ‘.json‘, JSON.stringify(geojson), function () {36 console.info(item.name + ‘ ok.‘);37  })38  })39 })

 

相关文章