Implementation in Elixir
Concept of implementing the filtering/sorting based on geo is going to be same, you can implement the same in any programming languages (e.g Javascript, Python). Here I would like to share, how we can implement the same in Elixir programming language.
Implement dynamic location filtering using PostGIS
In this section, we are exploring an example to see how provider dynamic location filtering will work in action with the PostGIS. And we are leveraging the library GeoPostGI for this implementation. I am assuming that you have mix project with PostgreSQL database configured already:
1. Enable/Create PostGIS Extension in PostgreSQL Schema
Be sure to enable the PostGIS extension if you haven't already done so (you might need DBA help to enable the extension if you are using AWS Aurora).
2. Install GeoPostGIS library
The package can be installed by adding :geo_postgis
to your list of dependencies in mix.exs
.
3. Add a column of type "geometry" in your table
Assuming you have enabled the PostGIS extension in your schema. Now you can create Ecto migration for creating a table with the geometry column.
4. Define a column with type geometry for Ecto Schema and extend the typing
Geo.PostGIS.Geometry
type is not available by default so we need to extend the Ecto typings by creating a new Module.
and update the repo config:
5. Insert multiple points (longitude/latitude) into the column
We can add a collection of points (longitude/latitude pair) into the column, we just need to cast a map to a struct in the following format:
%Geo.MultiPoint{coordinates: [{long, lat}], srid: 4326}
since our column type is Geo.PostGIS.Geometry and this can support all the Geometry types i.e. Point, MultiPoint, Polygon.
In PostGIS, Order of longitude and latitude matter in the pair, first should be longitude and then second should be latitude otherwise you might get incorrect results.
6. Write filters/sort query in PostGIS
Internally geo_postgis
function st_dwithin_in_meters
casts the geometries given to geographies to check for distance in meters if they areβt in geographies.
In order to filter & sort the Service provider by their closeness, we need center point ( means longitude/latitude) and radius in meters.
7. Create Index to Speed-up the geo-distance queries in PostGIS
Creating a Spatial index to boost up the geospatial query performance and our column physical_locations
is a type of geography
we can directly create an index on this column but If we need to query on geometry
type we need to create a spatial index by casting into geometry
type.
Last updated