Please note: This article discusses Stitch. Stitch is now MongoDB Realm.All the same features and functionality, now with a new name. Learn more
here. We will be updating this articlein due course.
For a lot of organizations, when it comes to location, geofencing isoften a very desirable or required feature. In case you're unfamiliar, ageofence can be thought of as a virtual perimeter for a geographic area.Often, you'll want to know when something enters or exits that geofenceso that you can apply your own business logic. Such logic might includesending a notification or updating something in your database.
MongoDB supports GeoJSON data and offers quite a few operators that makeworking the location data easy.
When it comes to geofencing, why would you want to use a database likeMongoDB rather than defining boundaries directly within yourclient-facing application? Sure, it might be easy to define and manageone or two boundaries, but when you're working at scale, checking to seeif something has exited or entered one of many boundaries could be ahassle.
In this tutorial, we're going to explore the$nearand$geoIntersectsoperators within MongoDB to define geofences and see if we're within thefences. For the visual aspect of things, we're going to make use ofMapbox for showing our geofences and ourlocation.
To get an idea of what we're going to build, take a look at thefollowing animated image:
We're going to implement functionality where a map is displayed andpolygon shapes are rendered based on data from within MongoDB. When wemove the marker around on the map to simulate actual changes inlocation, we're going to determine whether or not we've entered orexited a geofence.
There are a few moving pieces for this particular tutorial, so it isimportant that the prerequisites are met prior to starting:
Must have a Mapbox account with an access token generated.(Video) Geospatial Queries In MongoDB - Working With Location Based Data - Danny Lane
Must have a MongoDB Atlas cluster available.
Mapbox is a service, not affiliated with MongoDB. To render a map alongwith 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'llneed to be using MongoDB Atlas.
MongoDB Atlas can be used to deploy an M0sized cluster of MongoDB for FREE.
The MongoDB Atlas cluster should have a location_services databasewith a geofences collection.
Understanding the GeoJSON Data to Represent Fenced Regions
To use the geospatial functionality that MongoDB offers, the data storedwithin MongoDB must be valid GeoJSON data. At the end of the day,GeoJSON is still JSON, which plays very nicely with MongoDB, but thereis a specific schema that must be followed. To learn more about GeoJSON,visit the specification documentation.
For our example, we're going to be working with Polygon and Point data.Take the following document model:
In the above example, the
region represents our GeoJSON data andeverything above it such as
name represents any additional data thatwe want to store for the particular document. A realistic example to theabove model might look something like this:
We're naming any of our possible fenced regions. This could be useful toa lot of organizations. For example, maybe you're a business withseveral franchise locations. You could geofence the location and name itsomething like the address, store number, etc.
To get the performance we need from our geospatial data and to be ableto use certain operators, we're going to need to create an index on ourcollection. The index looks something like the following:
The index can be created through Atlas, Compass, and with the CLI. Thegoal here is to make sure the
region field is a
Configuring MongoDB Stitch for Client-Facing Application Interactions
Rather than creating a backend application to interact with thedatabase, we're going to make use of MongoDB Stitch. Essentially, theclient-facing application will use the Stitch SDK to authenticate beforeinteracting with the data.
Within the MongoDB Cloud, choose to createa new Stitch application if you don't already have one that you wish touse. Make sure that the application is using the cluster that has yourgeofencing data.
Within the Stitch dashboard, choose the Rules tab and create a newset of permissions for the geofences collection. For this particularexample, the Users can only read all data permission template isfine.
Next, we'll want to choose an authentication mechanism. In the Userstab, choose Providers, and enable the anonymous authenticationprovider. In a more realistic production scenario, you'll likely want tocreate geofences that have stricter users and rules design.
Before moving onto actually creating an application, make note of yourApp ID within Stitch, as it will be necessary for connecting.
Interacting with the Geofences using Mapbox and MongoDB Geospatial Queries
With all the configuration out of the way, we can move into the fun partof creating an attractive client-facing application that queries thegeospatial data in MongoDB and renders it on a map.
On your computer, create an index.html file with the followingboilerplate 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> tagthat follows.
<script> tag, the first things we want to accomplish arearound connecting to MongoDB Stitch and configuring map:
The map should be centered somewhere around Tracy, CA, and MongoDBStitch was configured to use the location_services database. Makesure to swap the tokens with your actual Mapbox and Stitch tokens.
The next step is to populate the map with markers and polygons when itloads:
In the above
load event, we are creating a marker somewhere outsidethe center of the map and one single polygon shape. The thing is, wedon't want to hard-code our polygon shapes that represent geofenceregions. Instead, add the GeoJSON data to MongoDB along with otherpossible fences.
We can change our
load event to the following:
In the above code, we query our collection for all documents and addthem each as a layer on the map. We can do better though. In the aboveexample, the geofences amount could be quite large and it doesn'tnecessarily make sense to show all the fences that aren't even remotelyclose to the current location. This would slow down the application forthe client.
Instead, we can change the query to the following:
In the above code, we're saying that we only want geofence results thatare within 50,000 meters of our center point coordinate set. While ourexample doesn't have many documents, this could be very beneficial interms of performance.
Depending on the geofence data in MongoDB, you likely have some polygonsdrawn on the map as well as your marker. The next step is to move themarker around to simulate a change in location. We can do this with the
click event for Mapbox:
In the above code we make use of the
$geoIntersects operator in ourquery. What this is doing is returning all documents where our pointsits within the polygon shape. The marker is updated to wherever the mapwas clicked.
If there is an intersection, we just print out the first result to analert. We do this because there could be overlapping geofences and forthe scope of this example, we don't need to worry about that.
You just saw how to leverage MongoDB and its ability to do geospatialqueries to create geofences for a maps and location services typeapplication. In the application we built, we stored GeoJSON data withinMongoDB and queried for it using the
$geoIntersectsoperators. This allowed us to figure out what data we wanted based on apoint location. We made use of Mapbox to give us a visual element as towhether or not our queries would return data.