2012-10-07 41 views
2

我想从一个SQL查询构建一个GeoJSON对象到postgis postgresql数据库中的一些GIS点数据。下面是我的node.js app.js的一个片段。来自postgis的格式geojson

据我了解,构建类型和功能,但不知道如何将属性数组附加到每个GeoJSON记录(在下面,它都在最后呈现,独立于(不与)特征)。

问题:我需要做什么以便为构建GeoJSON的循环中的每个记录附加(整理)所以它看起来更像这样http://www.geojson.org/geojson-spec.html#examples

`function GrabData(bounds, res){ 

    pg.connect(conn, function(err, client){ 

    var moisql = 'SELECT ttl, (ST_AsGeoJSON(the_geom)) as locale from cpag;' 


    client.query(moisql, function(err, result){ 
    var featureCollection = new FeatureCollection(); 

    for(i=0; i<result.rows.length; i++){ 
     featureCollection.features[i] = JSON.parse(result.rows[i].locale); 
     featureCollection.properties[i] = JSON.parse(result.rows[i].ttl); //this is wrong 
    } 

    res.send(featureCollection); 
    }); 

}); 
} 

function FeatureCollection(){ 
    this.type = 'FeatureCollection'; 
    this.features = new Array(); 
    this.properties = new Object; //this is wrong 
} 

`

+1

它看起来像你需要使用一个变通;见http://www.postgresonline.com/journal/archives/253-PostgreSQL-9.2-native-json-type-support.html –

+0

是的,你可能是正确的,但看起来像我将不得不更新我的postgres :( – roy

回答

3

这应该做的工作:

... 
for(i=0; i<result.rows.length; i++){ 
    var feature = new Feature(); 
    feature.geometry = JSON.parse(result.rows[i].locale); 
    feature.properties = {"TTL", result.rows[i].ttl}; 
    featureCollection.features.push(feature); 
} 
... 

使用:

function FeatureCollection(){ 
    this.type = 'FeatureCollection'; 
    this.features = new Array(); 
} 

function Feature(){ 
    this.type = 'Feature'; 
    this.geometry = new Object; 
    this.properties = new Object; 
} 
1

我最近写了一个小的辅助模块,用于这一目的。这是非常简单的使用 -

var postgeo = require("postgeo"); 

postgeo.connect("postgres://[email protected]:port/database"); 

postgeo.query("SELECT id, name ST_AsGeoJSON(geom) AS geometry FROM table", "geojson", function(data) { 
    console.log(data); 
}); 

您可以在这里找到回购 - https://github.com/jczaplew/postgeo