CartoDB+Firebase: Object tracking

CartoDB is built on top of PostgreSQL and PostGIS for making maps on the web fun and easy. Firebase is an awesome platform for pushing and receiving updates, i.e., making realtime applications. There are a bunch of users out there who want to track objects on maps, but also want to understand their movements over time. With CartoDB, you can store the object location data permanetly (or over some recent interval), visualize it, and begin asking geospatial questions like, “How far did this bus travel today?”.

San Francisco Muni

Firebase provides some incredibly realtime transit datasets. Check out all the buses from San Francisco’s Muni system.

We can listen for changes to the dataset behind this map and insert a new row into a CartoDB table for each new location reading with its timestamp. For this demo, we only want to keep records for the past 24 hours. We can quickly add a trigger that will discard our old data whenever new data arrives.

CREATE OR REPLACE FUNCTION clearOld() RETURNS TRIGGER AS $$
    BEGIN
        DELETE FROM sf_muni WHERE created_at < now()-'1 day'::interval;
        RETURN NEW;
    END;
$$ language plpgsql;

CREATE TRIGGER clearOldOnInsert
    AFTER INSERT ON sf_muni
    FOR EACH STATEMENT
    EXECUTE PROCEDURE clearOld();

After animating these rows with CartoDB’s Torque library, we see the buses moving around the city. Notice the hotspots (the Muni stations), the reduction in activity at night, and the higher speeds on the freeways. There’s a lot we can immediately understand by just looking at the data change over time.

Since we have the historical records of each bus, it’s easy to leverage PostGIS functions within CartoDB to answer our question above about how far a bus has traveled.

SELECT ST_LENGTH(ST_MakeLine(the_geom_webmercator ORDER BY created_at ASC)) AS sum FROM sf_muni WHERE id <BUS_ID>

Check out the live demo. Click on some buses and see how far they’ve gone today.

Displaying a few hundred objects on a map is something you can do by default with the Google Maps API. With CartodB on Google Cloud Platform, you can begin visualizing millions of historical traces and begin asking interesting geospatial questions. Firebase provides an extremely easy to use and robust data source for object tracking with CartoDB.

Related Posts

Ready to optimize your territories with Location Intelligence?

Close circle icon

Contact us

Please fill out the below form and we'll be in touch real soon.