Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a PostGIS GEOMETRY Point in Sequelize ORM?

I am trying to insert a row in a table that has a geometry column in Sequelize.js ORM. I have latitude, longitude and altitude and need to convert it to a point first so I can Insert it as a geometry.

The PostGIS stored procedure that does the converting is

ST_MakePoint( longitude, latitude, altitude ) 

To Insert a row I am using the sequelize model.create function

models.Data.create({    
  location: "ST_MakePoint("+request.params.lon+", "+request.params.lat+", "+request.params.alt+")", // PSUEDO code, How can I call this function?
  speed: request.params.spd,
  azimuth: request.params.azi,
  accuracy: request.params.acc
});

Now what I want to do Is make the field location have the returned result of "ST_MakePoint("+request.params.lon+", "+request.params.lat+", "+request.params.alt+")" when I insert the row.

How can I do that?

like image 732
Muhamed Krlić Avatar asked Aug 17 '15 21:08

Muhamed Krlić


2 Answers

Expanding on l0oky's answer, the integration test has a lot of good clues on how to use the json with varying types of Geometry. Basically, it appears that sequelize will stringify the provided geometry object assuming that it is valid GeoJSON and pipe that into the PostGIS function ST_GeomFromGeoJSON. Therefore, one can just follow the GeoJSON spec for geometry objects.

Points:

var point = { type: 'Point', coordinates: [39.807222,-76.984722]};

User.create({username: 'username', geometry: point }).then(function(newUser) {
...
});

Linestrings:

var line = { type: 'LineString', 'coordinates': [ [100.0, 0.0], [101.0, 1.0] ] };

User.create({username: 'username', geometry: line }).then(function(newUser) {
...
});

Polygons:

var polygon = { type: 'Polygon', coordinates: [
             [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
               [100.0, 1.0], [100.0, 0.0] ]
             ]};

User.create({username: 'username', geometry: polygon }).then(function(newUser) {
...
});

Setting a custom SRID:

var point = { 
  type: 'Point', 
  coordinates: [39.807222,-76.984722],
  crs: { type: 'name', properties: { name: 'EPSG:4326'} }
};

User.create({username: 'username', geometry: point }).then(function(newUser) {
...
});
like image 132
Evan Siroky Avatar answered Nov 17 '22 07:11

Evan Siroky


After a bit of researching I found that Sequelize 3.5.1 ( is supporting GEOMETRY ) had a test that inserts a Point.

var point = { type: 'Point', coordinates: [39.807222,-76.984722] }; 
return User.create({ username: 'user', email: ['[email protected]'], location: point})

Where location is a GEOMETRY field. This way I don't need to call ST_MakePoint manually, sequelize takes care of that.

like image 6
Muhamed Krlić Avatar answered Nov 17 '22 05:11

Muhamed Krlić