5

I am trying to build a GeoJSON object from a SQL query to some GIS point data in a postgis postgresql database. A snippet of my node.js app.js is below.

As it stands I understand building the type and features, but don't know how to attach a properties properties to each GeoJSON record (in the below, it all renders at the end, separate from (not collated with) the features).

THE QUESTION: What do I need to do so that the properties attach (collate) for each record in the loop that builds the GeoJSON So that it looks more like this 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
 }
Devdatta Tengshe
41.8k37 gold badges147 silver badges267 bronze badges
asked Oct 7, 2012 at 15:31

1 Answer 1

5

This function should work for you; just pass the result.rows object as the argument;

 toGeoJson: function(rows){
 var obj, i;
 obj = {
 type: "FeatureCollection",
 features: []
 };
 for (i = 0; i < rows.length; i++) {
 var item, feature, geometry;
 item = rows[i];
 geometry = JSON.parse(item.geometry);
 delete item.geometry;
 feature = {
 type: "Feature",
 properties: item,
 geometry: geometry
 }
 obj.features.push(feature);
 } 
 return obj;
 }
answered Oct 17, 2012 at 23:30
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.