Setting up Postgis it self is it not much a hustle. I mean, all you need to do is make sure you have Postgis installed which might already be done for you depending on how you are running your Postgres database. ie: if you are using Postgres from a cloud provider, then you already have it as part of the Postgres service. If you are using postgres service from docker, then all you need to do is replace your postgres docker image with postgis/postgis docker image and you are good. What if i’m running postgres natively on my laptop , you might be wondering ? Then kindly follow the steps here in the official docs, since the focus of this blog post is not to learn how to install postgis.
With the context above, the assumption is you already have Postgis installed and you just want to see the code on how to configure and use it within adonisJS (lucid ORM). To enable postgis, we need to create a migration file with the below content in the migration file
CREATE EXTENSION IF NOT EXISTS postgis;
What the above SQL statement does is to configure and enable the postgis extension within the database you are connected to. You will notice about 2 tables created in the db, along with a dozen functions.
Now the next step is actually using the postgis we just installed. To do so, we will create a sample database table called user_profile which would have the below columns
id - primary key
full_name - User’s full name
location - The User’s location (in coordinates) ie: 5.6393728,-0.1709543
NB: To describe a column to be of a geo spatial type, we need to use either the geography or geometry data type. Either of them will work, but if you want to know the technical details and the difference between the 2, head on to read more here
Talk is cheap, let me see the code ):
import { BaseSchema } from '@adonisjs/lucid/schema'
export default class extends BaseSchema {
protected tableName = 'user_profile'
public async up() {
this.schema.createTable(this.tableName, (table) => {
table.increments('id')
table.string('full_name')
table.geometry('location')
})
}
public async down() {
this.schema.dropTable(this.tableName)
}
}
As seen in the code above, you will notice we are using a special data type called geometry to define the column data type for the location column.
Now that we are done creating our table, we will need a model to interact with our data. To do so we will use the code below