当前位置:首页 > Web开发 > 正文

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

2024-03-31 Web开发

如果能使用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": 1 10 }, 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 // 盘问sql 2 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东西,怎么破解qq空间访问权限文库 ,放入数组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": 2 15 }, 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": features 5 }

最后将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": features 34 } 35 fs.writeFile(‘./result/‘ + item.name + ‘.json‘, JSON.stringify(geojson), function () { 36 console.info(item.name + ‘ ok.‘); 37 }) 38 }) 39 })

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

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/29340.html