Using React and Mapbox to Map Bus Routes
My goal was to map all Calgary Transit bus routes in a quick, simply UI interface. That lead me to consider pairing React and Mapbox. Since I’m using the City of Calgary Open Data API (through Socrata) there was no need to set up a database or model using the standard Model Viewer Controller (MVC) architecture so that made things a little simpler.
React and Mapbox work really well together in building quick, efficient user interfaces. Mapbox’s blog has an intro (Mapbox GS JS + React) in integrating the two and was my starting point in getting the map up and running.
After getting all the APIs calls working, I ran into issues updating the data source. Unfortunately, there’s limited documentation on the Mapbox+React combination so I had to do some digging of my own. This first led me to understanding the Lifecycle of a React Component. It’s important to load the API calls and Mapbox map objects in
componentDidMount(). Successfully updating the data source involved an implementation of Mapbox’s
setData() method that did the trick in updating my data source and reloading the map for an onChange event.
Add in a little bit of Turf for simple geospatial analysis and the outcome is a simple, fast loading map that shows Calgary Transit bus routes. You can see the source code on github and the final working example.