Location Geofencing with MongoDB, Stitch, and Mapbox
Rate this tutorial
For a lot of organizations, when it comes to location, geofencing is often a very desirable or required feature. In case you're unfamiliar, a geofence can be thought of as a virtual perimeter for a geographic area. Often, you'll want to know when something enters or exits that geofence so that you can apply your own business logic. Such logic might include sending a notification or updating something in your database.
MongoDB supports GeoJSON data and offers quite a few operators that make working the location data easy.
When it comes to geofencing, why would you want to use a database like MongoDB rather than defining boundaries directly within your client-facing application? Sure, it might be easy to define and manage one or two boundaries, but when you're working at scale, checking to see if something has exited or entered one of many boundaries could be a hassle.
To get an idea of what we're going to build, take a look at the following animated image:
We're going to implement functionality where a map is displayed and polygon shapes are rendered based on data from within MongoDB. When we move the marker around on the map to simulate actual changes in location, we're going to determine whether or not we've entered or exited a geofence.
There are a few moving pieces for this particular tutorial, so it is important that the prerequisites are met prior to starting:
- Must have a Mapbox account with an access token generated.
- Must have a MongoDB Atlas cluster available.
Mapbox is a service, not affiliated with MongoDB. To render a map along with shapes and markers, an account is necessary. For this example, everything can be accomplished within the Mapbox free tier.
Because we'll be using MongoDB Stitch in connection with Mapbox, we'll need to be using MongoDB Atlas.
The MongoDB Atlas cluster should have a location_services database with a geofences collection.
For our example, we're going to be working with Polygon and Point data. Take the following document model:
In the above example, the
regionrepresents our GeoJSON data and everything above it such as
namerepresents any additional data that we want to store for the particular document. A realistic example to the above model might look something like this:
We're naming any of our possible fenced regions. This could be useful to a lot of organizations. For example, maybe you're a business with several franchise locations. You could geofence the location and name it something like the address, store number, etc.
To get the performance we need from our geospatial data and to be able to use certain operators, we're going to need to create an index on our collection. The index looks something like the following:
The index can be created through Atlas, Compass, and with the CLI. The goal here is to make sure the
regionfield is a
Rather than creating a backend application to interact with the database, we're going to make use of MongoDB Stitch. Essentially, the client-facing application will use the Stitch SDK to authenticate before interacting with the data.
Within the Stitch dashboard, choose the Rules tab and create a new set of permissions for the geofences collection. For this particular example, the Users can only read all data permission template is fine.
Next, we'll want to choose an authentication mechanism. In the Users tab, choose Providers, and enable the anonymous authentication provider. In a more realistic production scenario, you'll likely want to create geofences that have stricter users and rules design.
Before moving onto actually creating an application, make note of your App ID within Stitch, as it will be necessary for connecting.
With all the configuration out of the way, we can move into the fun part of creating an attractive client-facing application that queries the geospatial data in MongoDB and renders it on a map.
On your computer, create an index.html file with the following boilerplate code:
In the above HTML, we're importing the Mapbox and MongoDB Stitch SDKs, and we are defining an HTML container to hold our interactive map. Interacting with MongoDB and the map will be done in the
<script>tag that follows.
<script>tag, the first things we want to accomplish are around connecting to MongoDB Stitch and configuring map:
The map should be centered somewhere around Tracy, CA, and MongoDB Stitch was configured to use the location_services database. Make sure to swap the tokens with your actual Mapbox and Stitch tokens.
The next step is to populate the map with markers and polygons when it loads:
In the above
loadevent, we are creating a marker somewhere outside the center of the map and one single polygon shape. The thing is, we don't want to hard-code our polygon shapes that represent geofence regions. Instead, add the GeoJSON data to MongoDB along with other possible fences.
We can change our
loadevent to the following:
In the above code, we query our collection for all documents and add them each as a layer on the map. We can do better though. In the above example, the geofences amount could be quite large and it doesn't necessarily make sense to show all the fences that aren't even remotely close to the current location. This would slow down the application for the client.
Instead, we can change the query to the following:
In the above code, we're saying that we only want geofence results that are within 50,000 meters of our center point coordinate set. While our example doesn't have many documents, this could be very beneficial in terms of performance.
Depending on the geofence data in MongoDB, you likely have some polygons drawn on the map as well as your marker. The next step is to move the marker around to simulate a change in location. We can do this with the
clickevent for Mapbox:
In the above code we make use of the
$geoIntersectsoperator in our query. What this is doing is returning all documents where our point sits within the polygon shape. The marker is updated to wherever the map was clicked.
If there is an intersection, we just print out the first result to an alert. We do this because there could be overlapping geofences and for the scope of this example, we don't need to worry about that.
You just saw how to leverage MongoDB and its ability to do geospatial queries to create geofences for a maps and location services type application. In the application we built, we stored GeoJSON data within MongoDB and queried for it using the
$geoIntersectsoperators. This allowed us to figure out what data we wanted based on a point location. We made use of Mapbox to give us a visual element as to whether or not our queries would return data.