2012-10-07 43 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