Mapnik renders map with datasource to empty vector tile - mapnik

sorry if this a novice question. I am using node-mapnik to generate vector tiles from a database query, but the vector tiles always return empty, whereas I am pretty sure postgis actually returns data (tested the query separately on psql, with the same bounding box).
Is there something obvious missing in the following code ? I have not added a style to the map layer rendered to vector tile, because I thought that vector tiles are not actually "rendered" on the server, is this the issue ? Thanks for your answer,
pgMapRouter.get('/:z/:x/:y.pbf', function(req, res) {
var bbox = mercator.bbox(
+req.params.x,
+req.params.y,
+req.params.z,
false,
'4326'
);
var map = new mapnik.Map(256, 256);
map.extent = bbox;
var layer = new mapnik.Layer('fixture_layer');
layer.datasource = new mapnik.Datasource({
type: 'postgis',
dbname: 'citydb',
table: 'test2',
user: 'postgres',
password: 'postgres',
host: 'localhost',
port:5432,
geometry_field: 'wkb_geometry',
srid:4326,
extent: bbox
});
map.add_layer(layer);
var vtile = new mapnik.VectorTile(+req.params.z, +req.params.x, +req.params.y);
map.render(vtile, function (err, vtile) {
if (err) console.log(err);
res.setHeader('Content-Encoding', 'deflate');
res.setHeader('Content-Type', 'application/x-protobuf');
zlib.deflate(vtile.getData(), function(err, pbf) {
console.log(mapnik.VectorTile.info(pbf))
res.send(pbf);
});
});
});

Related

Orientdb query approach to get properties of vertices and edges

Im a newbie to orient db .I have a vertex user which has properties adress,name and another vertex Images with properties imagename,date.Both are connected by and edge postedby.Now I want to write a query to select all images posted by a user with all the properties of both the vertices.How can I write the query to get this.I use orientjs in my project
Try this:
var OrientDB = require('orientjs');
var db = OrientDB({
host: 'localhost',
port: 2424,
});
var db = db.use({
name: '<db name>',
username: '<username>',
password: '<pwd>'
});
db.query('select address, name, out("postedby").imagename as imagename, out("postedby").date as date from User where name = "<insert a name>" unwind imagename,date')
.then(function (response) {
console.log(response);
});
db.close();
Hope it helps
Regards

Not able to use .save() while updating (put request) to a mongoose model (with strict set to false)

So I am building yet another CRUD app using the MERN stack (let's use foo as the example). Problem is that in this project I am trying to support an unstructured data stream, so I am setting the Schema to strict:false in the Data Model. All my requests work (get, delete, & post) but when I started working on editing the properties of a foo and sending it to Mongo I get this error.
TypeError: foo.save is not a function
Here's what my Routes look like for my API
router.route('/foos/:foo_id')
.put(function(req, res){
foo.findById(req.params.foo_id, function(err, foo) {
if (err)
res.send(err);
foo = req.body;
foo.save(function(err) {
if(err)
res.send(err);
res.json({message: 'foo Updated'});
});
})
});
Here's what my data model looks like:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var FooSchema = new Schema({
bar: String,
foobar: String,
}, { strict: false })
module.exports = mongoose.model('foo', FooSchema);
Here's my reducer:
case 'SAVE_FOO':
var id = action.foo._id;
var fooEdits = action.foo;
//serialize data to send to Mongo
function serialize(obj) {
var str = [];
for(var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
fetch('http://localhost:7770/api/foos/' + id, {
method: 'put',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: serialize(fooEdits)
})
return state;
I am guess this is because i am overwriting the original schema i set for that foo. It works if I pass values defined in my schema, so if I change foo = req.body to foo.bar = req.body.bar it works.
The thing is I want to be able to pass whatever properties into this model and save to mongo, without defining it in the Schema. Is this possible or am I creating the most vulnerable CRUD app known to mankind?
I was thinking I could update my schema to have a customObj:{} then pass all custom properties in there. Then i could do foo.customObj = req.body.customObj, but that seems wrong...
Any help would be greatly appreciated, also this is my first post on Stack Overflow, so please let me know how I could better phrase my question or examples. Thanks!
foo = req.body;
change to
Object.assign(foo,req.body);

Mongoose, geospatial query for users

I'm currently working with nodeJS, using express and mongoDB and mongoose for an ORM. When I create a User and save them to the database I would like to query their location and save it. This is what I am currently doing, I have a UserSchema and a location Schema.
My userSchema just has the location stored as a string and in the location Schema itself I have
var locationSchema = new mongoose.Schema({
name: String,
loc: {
type: [Number],
index: '2d'
}
});
mongoose.model('Location', LocationSchema);
And then in my controller, I have the following
import json from '../helpers/json;
import mongoose from 'mongoose';
var User = mongoose.model('User);
module.exports = function() {
var obj = {};
obj.create = function (req, res) {
var user = new User(req.body);
user.roles = ['authenticated']
user.location = getLocation(req);
user.save(function (err) {
if (err) {
return json.bad(err, res);
}
json.good({
record: user,
});
});
};
return obj;
function getLocation (req) {
var limit = req.query.limit || 10;
var maxDistance = req.query.distance || 1;
maxDistance /= 6371;
var coords = [];
coords[0] = req.query.longitude;
coords[1] = req.query.lattitude;
Location.findOne({
loc: {
$near: coords,
$maxDistance: maxDistance
}
}).limit(limit).exec(function (err, location) {
if (err) {
console.log(err);
}
return location.name;
});
}
};
I have also tried using location.find instead of findOne and returning locations[0].name.
The error is thrown says cast to the number failed for value undefined at loc.
Do I need to send the location data to the server from the client side? If so, is there a best method to implement this? I have heard of the HTML5 Geolocation API, but I have never utilized it.
Thank you!
!!! -- UPDATE --- !!
I have started using the Geolocation API on the client side to send this data to the server in the request. I am using angular on the client side like so
(function() {
'use strict';
angular.module('opinionated.authentication')
.controller('SignupController', SignupController);
/* #ngInject */
function SignupController ($state, appUsers, appToast) {
var vm = this;
vm.reset = reset;
vm.create = create;
vm.user = {
name: '',
username: '',
email: '',
password: ''
};
vm.location = {
lattitude: '',
longitude: ''
};
function create = (isValid) {
if (isValid) {
var user = new appUsers.single({
name: vm.user.name,
username: vm.user.username,
email: vm.user.email,
password: vm.user.password,
lattitude: vm.location.lattitude,
longitutde: vm.location.longitude
});
user.$save(function (response) {
if (response.success) {
appToast('Welcome to Opinionated, ' + response.res.record.name);
$state.go('authentication.wizard')
} else {
appToast(response.res.messsage);
}
});
} else {
appToast('Hmm... Something seems to be missing');
}
}
function getPosition() {
navigator.geolocation.getPosition(updatePosition);
}
function updatePosition (position) {
vm.location.lattitude = position.coords.lattitude;
vm.location.longitutde = position.coords.longitude;
}
getPosition();
....
I think it has something to do with how I am getting the coordinates now. My browser prompts me for permission to use my location, so I am at least requesting the data. However, I changed my User Schema to save the lat and long and neither of these values are being saved upon success.
I found my error. I did need to include the Geolocation API to get the users coordinates. I then just saved the coordinates to the database and am using mongo's geo service from there! Everything works fine now.

Bookshelf.js polymorphic relation query returns empty array

I defined my relations as required. A user has multiple photos and an a photo is belong to a user.
Why my query returns an empty photos[] array? (I'm attempting to get all photos of a given user)
Docs : http://bookshelfjs.org/#polymorphic
My image table structured like this:
images
id (auto increment and primary key)
imageable_type (user is given)
imageable_id (user_id is given)
models.js
var image = db.Model.extend({
tableName: 'images',
imageable: function () {
return this.morphTo('imageable', user);
}
});
var user = db.Model.extend({
tableName: 'users',
hasTimestamps: true,
photos: function () {
return this.morphMany(image, 'imageable');
}
});
module.exports.user = user;
module.exports.image = image;
app.js
var user = require('./models').user;
var image = require('./models').image;
app.get('/photos', function (req, res) {
user.where('id' , 1).fetchAll({withRelated: ['photos']}).then(function (data) {
data = data.toJSON();
res.send(data);
});
});
Problem solved.
It turns out you need to use the plural table name in images table, which is users in this case.

Mongoose - persistent `virtual` field?

Ok, I have node as backend, it has the following Mongoose model:
var SomeSchema = new Schema({
name: {type: String, required: true},
iplanned: {type: String, default:60}
});
SomeSchema.virtual('planned')
.get(function () {
return parseInt(this.iplanned / 60, 10) + ' mins';
})
.set(function (val) {
this.iplanned = parseInt(val, 10) * 60;
});
someModel = mongoose.model('Some', SomeSchema);
So far it is good, from node.js side of things I can work with the records and access this planned field as I like.
The following is a simple responder to serve this list through http:
exports.list = function (req, res) {
someModel.find(function (err, deeds) {
return res.send(deeds);
});
});
And here's the problem - the virtual field planned is not included in each record (well, it is understandable, sort of). Is there a way to inject somehow my virtual field to each record? Or I have to do the virtual conversion on a front end as well? (Yeah, I know that there's Meteor.js out there, trying go without it here).
In your schema you should redefine toJSON() method:
SomeSchema.methods.toJSON = function () {
var obj = this.toObject();
obj.planned = this.planned;
return obj;
};

Resources