Location Geofencing with MongoDB, Stitch, and Mapbox | MongoDB (2023)

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:

Location Geofencing with MongoDB, Stitch, and Mapbox | MongoDB (1)

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.

The Requirements

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:

Location Geofencing with MongoDB, Stitch, and Mapbox | MongoDB (2)

In the above example, the

(Video) Scalable Realm Sync Design

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:

Location Geofencing with MongoDB, Stitch, and Mapbox | MongoDB (3)

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:

Location Geofencing with MongoDB, Stitch, and Mapbox | MongoDB (4)

The index can be created through Atlas, Compass, and with the CLI. Thegoal 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 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.

Location Geofencing with MongoDB, Stitch, and Mapbox | MongoDB (5)

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.

Location Geofencing with MongoDB, Stitch, and Mapbox | MongoDB (6)

Before moving onto actually creating an application, make note of yourApp ID within Stitch, as it will be necessary for connecting.

(Video) Exploring Amazon Location service - Devs in the Shed

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:

Location Geofencing with MongoDB, Stitch, and Mapbox | MongoDB (7)

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.

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

Location Geofencing with MongoDB, Stitch, and Mapbox | MongoDB (8)

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:

Location Geofencing with MongoDB, Stitch, and Mapbox | MongoDB (9)

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:

(Video) The Tech Behind Connected Car

Location Geofencing with MongoDB, Stitch, and Mapbox | MongoDB (10)

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:

Location Geofencing with MongoDB, Stitch, and Mapbox | MongoDB (11)

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

Location Geofencing with MongoDB, Stitch, and Mapbox | MongoDB (12)

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.

Conclusion

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 $near and $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.

(Video) ASEAN Partner Webinar Series How Boost and Aspire NXT Make Mass Personalization a Reality

Videos

1. Webinar Recording from May 20th 2021: When the model is the code (and a trip to the Bahamas)
(Blog LieberLieber)
2. Paul Kinlan: The headless web and the future of the web on mobile.
(ColdFront)
3. Planet Scale SQL For The New Generation Of Applications - Episode 115
(Tobias Macey)
4. ML/AI Based Solution for 1-1 Personalisation in Fashion Retail
(Oracle Developers)
5. Getting Started with Hugo for Static Site Generation
(The Polyglot Developer)
6. GraphConnect Europe 2015 / Aaron Wallace, Pitney Bowes - Mastering Customer Information
(Neo4j)
Top Articles
Latest Posts
Article information

Author: Nathanael Baumbach

Last Updated: 03/08/2023

Views: 5796

Rating: 4.4 / 5 (55 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Nathanael Baumbach

Birthday: 1998-12-02

Address: Apt. 829 751 Glover View, West Orlando, IN 22436

Phone: +901025288581

Job: Internal IT Coordinator

Hobby: Gunsmithing, Motor sports, Flying, Skiing, Hooping, Lego building, Ice skating

Introduction: My name is Nathanael Baumbach, I am a fantastic, nice, victorious, brave, healthy, cute, glorious person who loves writing and wants to share my knowledge and understanding with you.