Supabase

How to implement geospatial queries in Supabase?

Master geospatial queries in Supabase with this easy-to-follow guide. Uncover the best tools and tricks for managing spatial data seamlessly.

Developer profile skeleton
a developer thinking

Overview

Geospatial queries help manage geographical information, letting developers run spatial searches and calculations—crucial for map-related, location-based, or regional apps. Supabase, which is an open-source alternative to Firebase, comes with geospatial query support, thanks to its PostgreSQL base. It uses PostGIS, a spatial database extender for PostgreSQL, allowing for storage, querying, and manipulation of geospatial data. Grasping the connection between Supabase and PostGIS, along with a good handle on SQL for spatial functions, is essential for carrying out effective geospatial queries in any Supabase project.

Get a Free No-Code Consultation
Meet with Will, CEO at Bootstrapped to get a Free No-Code Consultation
Book a Call
Will Hawkins
CEO at Bootstrapped

How to implement geospatial queries in Supabase?

Step 1: Setting Up Your Supabase Project

  1. First things first, head over to supabase.com and either sign up or log in to your account.
  2. Once you're in, create a new project and fill in all the necessary details. Easy peasy!

Step 2: Configuring PostGIS Extension

  1. Navigate to your project dashboard and find the SQL editor.
  2. To enable the PostGIS extension, run this command:
CREATE EXTENSION IF NOT EXISTS postgis;

Step 3: Creating a Table with Geospatial Data

  1. Let's create a table with a geometry column. Run this SQL command:
CREATE TABLE locations (
  id serial PRIMARY KEY,
  name text,
  geom geometry(Point, 4326)
);
  1. Now, let's add some sample data with geographical coordinates:
INSERT INTO locations (name, geom)
VALUES 
('Location A', ST_SetSRID(ST_MakePoint(-73.935242, 40.730610), 4326)),
('Location B', ST_SetSRID(ST_MakePoint(-74.935242, 41.730610), 4326));

Step 4: Querying Geospatial Data

  1. To find locations within a certain distance from a given point, use the ST_DWithin function:
SELECT id, name 
FROM locations 
WHERE ST_DWithin(geom, ST_SetSRID(ST_MakePoint(-73.935242, 40.730610), 4326), 10000);

This query will return the locations within 10,000 meters of the specified point.

  1. To get the distance between two points, use the ST_Distance function:
SELECT id, name, ST_Distance(geom::geography, ST_SetSRID(ST_MakePoint(-73.935242, 40.730610), 4326)::geography) AS distance 
FROM locations;

This query will return the distance in meters from each location to the specified point.

Step 5: Using Supabase Client Libraries for Geospatial Queries

  1. Install the Supabase client library in your project. For JavaScript/Node.js, run:
npm install @supabase/supabase-js
  1. Initialize the Supabase client:
import { createClient } from '@supabase/supabase-js';

const supabaseUrl = 'https://xyzcompany.supabase.co';
const supabaseKey = 'your-anon-key';
const supabase = createClient(supabaseUrl, supabaseKey);
  1. Execute a geospatial query using the client library:
const { data, error } = await supabase
  .from('locations')
  .select('id, name')
  .filter('geom', 'st_dwithin', `SRID=4326;POINT(-73.935242 40.730610)`, 10000);

This query fetches the locations within 10,000 meters of the specified point using the Supabase client library.

Step 6: Visualizing Geospatial Data

  1. Use a mapping library like Leaflet or Mapbox to visualize geospatial data in your frontend application.
  2. Retrieve geospatial data from Supabase and plot it on the map. Here’s a basic example using Leaflet:
import L from 'leaflet';
import { createClient } from '@supabase/supabase-js';

const supabase = createClient('https://xyzcompany.supabase.co', 'your-anon-key');

const map = L.map('map').setView([40.730610, -73.935242], 12);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);

(async () => {
  const { data: locations, error } = await supabase
    .from('locations')
    .select('name, geom');

  locations.forEach(location => {
    const coordinates = location.geom.coordinates;
    L.marker([coordinates[1], coordinates[0]]).addTo(map)
      .bindPopup(location.name);
  });
})();

This guide covers the basics of implementing geospatial queries in Supabase, including setup, table creation, querying, and visualization.

Explore more Supabase tutorials

Complete Guide to Supabase: Tutorials, Tips, and Best Practices

Explore our Supabase tutorials directory - an essential resource for learning how to create, deploy and manage robust server-side applications with ease and efficiency.

Why are companies choosing Bootstrapped?

40-60%

Faster with no-code

Nocode tools allow us to develop and deploy your new application 40-60% faster than regular app development methods.

90 days

From idea to MVP

Save time, money, and energy with an optimized hiring process. Access a pool of experts who are sourced, vetted, and matched to meet your precise requirements.

1 283 apps

built by our developers

With the Bootstrapped platform, managing projects and developers has never been easier.

hero graphic

Our capabilities

Bootstrapped offers a comprehensive suite of capabilities tailored for startups. Our expertise spans web and mobile app development, utilizing the latest technologies to ensure high performance and scalability. The team excels in creating intuitive user interfaces and seamless user experiences. We employ agile methodologies for flexible and efficient project management, ensuring timely delivery and adaptability to changing requirements. Additionally, Bootstrapped provides continuous support and maintenance, helping startups grow and evolve their digital products. Our services are designed to be affordable and high-quality, making them an ideal partner for new ventures.

Engineered for you

1

Fast Development: Bootstrapped specializes in helping startup founders build web and mobile apps quickly, ensuring a fast go-to-market strategy.

2

Tailored Solutions: The company offers customized app development, adapting to specific business needs and goals, which ensures your app stands out in the competitive market.

3

Expert Team: With a team of experienced developers and designers, Bootstrapped ensures high-quality, reliable, and scalable app solutions.

4

Affordable Pricing: Ideal for startups, Bootstrapped offers cost-effective development services without compromising on quality.

5

Supportive Partnership: Beyond development, Bootstrapped provides ongoing support and consultation, fostering long-term success for your startup.

6

Agile Methodology: Utilizing agile development practices, Bootstrapped ensures flexibility, iterative progress, and swift adaptation to changes, enhancing project success.

Yes, if you can dream it, we can build it.