Location Geofencing with MongoDB, Stitch, and Mapbox

Published: May 28, 2020

  • Realm
  • JavaScript

By Nic Raboy


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 article in due course.

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.

In this tutorial, we're going to explore the $near and $geoIntersects operators within MongoDB to define geofences and see if we're within the fences. For the visual aspect of things, we're going to make use of Mapbox for showing our geofences and our location.

To get an idea of what we're going to build, take a look at the following animated image:

Animation of geofencing

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.

#The Requirements

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.

MongoDB Atlas can be used to deploy an M0 sized cluster of MongoDB for FREE.

The MongoDB Atlas cluster should have a location_services database with a geofences collection.

#Understanding the GeoJSON Data to Represent Fenced Regions

To use the geospatial functionality that MongoDB offers, the data stored within MongoDB must be valid GeoJSON data. At the end of the day, GeoJSON is still JSON, which plays very nicely with MongoDB, but there is 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:

2 "_id": ObjectId(),
3 "name": string,
4 "region": {
5 "type": string,
6 "coordinates": [
7 [
8 [double]
9 ]
10 ]
11 }

In the above example, the region represents our GeoJSON data and everything above it such as name represents any additional data that we want to store for the particular document. A realistic example to the above model might look something like this:

2 "_id": ObjectId("5ebdc11ab96302736c790694"),
3 "name": "tracy",
4 "region": {
5 "type": "Polygon",
6 "coordinates": [
7 [
8 [-121.56115581054638, 37.73644193427164],
9 [-121.33868266601519, 37.59729761382843],
10 [-121.31671000976553, 37.777700170855454],
11 [-121.56115581054638, 37.73644193427164]
12 ]
13 ]
14 }

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:

1db.geofences.createIndex({ region: "2dsphere" })

The index can be created through Atlas, Compass, and with the CLI. The goal here is to make sure the region field is a 2dsphere index.

#Configuring MongoDB Stitch for Client-Facing Application Interactions

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 MongoDB Cloud, choose to create a new Stitch application if you don't already have one that you wish to use. Make sure that the application is using the cluster that has your geofencing data.

applications in MongoDB Stitch

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.

activating anonymous authentication in MongoDB Stitch

Before moving onto actually creating an application, make note of your App 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 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:

1<!DOCTYPE html>
3 <script src="https://api.mapbox.com/mapbox-gl-js/v1.10.0/mapbox-gl.js"></script>
4 <link href="https://api.mapbox.com/mapbox-gl-js/v1.10.0/mapbox-gl.css" rel="stylesheet" />
5 <script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4.6.0/stitch.js"></script>
8 <body style="margin: 0">
9 <div id="map" style="width: 100vw; height: 100vh"></div>
10 <script> // Logic in here ... </script>
11 </body>

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.

Within the <script> tag, the first things we want to accomplish are around connecting to MongoDB Stitch and configuring map:

1const client = stitch.Stitch.initializeDefaultAppClient("MONGODB_STITCH_APP_ID_HERE");
2const db = client.getServiceClient(stitch.RemoteMongoClient.factory, "mongodb-atlas").db("location_services");
3let currentLocationMarker;
5client.auth.loginWithCredential(new stitch.AnonymousCredential());
7mapboxgl.accessToken = "MAPBOX_ACCESS_TOKEN_HERE";
8let map = new mapboxgl.Map({
9 container: "map",
10 style: "mapbox://styles/mapbox/streets-v11",
11 center: [-121.4252, 37.7397],
12 zoom: 9

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:

1map.on("load", async () => {
2 currentLocationMarker = new mapboxgl.Marker().setLngLat([-121.29473735351542, 37.94575186984845]).addTo(map);
3 map.addSource("UNIQUE_ID", {
4 "type": "geojson",
5 "data": {
6 "type": "Feature",
7 "geometry": {
8 "type": "Polygon",
9 "coordinates": [
10 [
11 [-121.56115581054638, 37.73644193427164],
12 [-121.33868266601519, 37.59729761382843],
13 [-121.31671000976553, 37.777700170855454],
14 [-121.56115581054638, 37.73644193427164]
15 ]
16 ]
17 }
18 }
19 });
20 map.addLayer({
21 "id": "UNIQUE_ID",
22 "type": "fill",
23 "source": "UNIQUE_ID",
24 "layout": {},
25 "paint": {
26 "fill-color": "#088",
27 "fill-opacity": 0.8
28 }
29 });

In the above load event, 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 load event to the following:

1map.on("load", async () => {
2 let fences = await db.collection("geofences").find({}).asArray();
3 currentLocationMarker = new mapboxgl.Marker().setLngLat([-121.29473735351542, 37.94575186984845]).addTo(map);
4 fences.forEach(fence => {
5 map.addSource(fence.name, {
6 "type": "geojson",
7 "data": {
8 "type": "Feature",
9 "geometry": fence.region
10 }
11 });
12 map.addLayer({
13 "id": fence.name,
14 "type": "fill",
15 "source": fence.name,
16 "layout": {},
17 "paint": {
18 "fill-color": "#088",
19 "fill-opacity": 0.8
20 }
21 });
22 });

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:

1let fences = await db.collection("geofences").find({
2 region: {
3 $near: {
4 $geometry: {
5 type: "Point",
6 coordinates: [-121.4252, 37.7397]
7 },
8 $maxDistance: 50000
9 }
10 }

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 click event for Mapbox:

1map.on("click", async (e) => {
2 currentLocationMarker.setLngLat([e.lngLat.lng, e.lngLat.lat]);
3 let result = await db.collection("geofences").find({
4 region: {
5 $geoIntersects: {
6 $geometry: {
7 type: "Point",
8 coordinates: [e.lngLat.lng, e.lngLat.lat]
9 }
10 }
11 }
12 }, { projection: { name: 1 }}).asArray();
13 if(result.length > 0) {
14 alert(`Within the ${result[0].name} fence!`);
15 }

In the above code we make use of the $geoIntersects operator 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 $near and $geoIntersects operators. 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.

More from this series

Maps and Geospatial Data
  • Location Geofencing with MongoDB, Stitch, and Mapbox
  • Real-Time Location Updates with MongoDB Stitch, Change Streams, and Mapbox
  • Searching for Nearby Points of Interest with MongoDB and Mapbox
MongoDB Icon
  • Developer Hub
  • Documentation
  • University
  • Community Forums

© MongoDB, Inc.