How to Create a Real-time Public Transportation Schedule App
Published: 2024-03-01 16:34:35

There is a place where real-time information, changing scenarios of public transportation systems, and the Internet of Things (IoT) meet—let's call it the Internet of Transportation Things (IoTT). One can think of it as a highly advanced and user-friendly transit app that functions with real-time data. With titans like IBM, Moovit, and Google Maps eyeing to capitalize on "Intelligent Transportation", IoTT is poised to revolutionize the way we perceive transportation, making it more accessible for daily commuters.

As a developer, particularly into mobile app development, you might wonder how this new development affects you and how you can get involved. Whether you're an iOS or Android enthusiast, a real-time data stream network like PubNub can be your gateway to navigate this sea change. This new wave of handling public transit information brings the exciting future of IoTT closer to reality, envisioning a time when you might be developing a transit app for mobile devices that enables devices to connect to a channel and communicate, broadcasting things like current locations or destinations. Imagine a future where all this real-time information helps in grouping transportation based on this information for superior efficiency.

PubNub is a powerful tool that is at the forefront of this evolution and continues to innovate with its state-of-the-art technology and trusted services in the field of IoT, backed by our renowned certifications and qualifications. This gives you the promising opportunity to create software applications that could redefine how transport systems work. These kinds of applications are becoming increasingly important in the transportation industry, proving to be beneficial for commuters, transit agencies, as well as transportation service providers.

So, how do you start? Let's get our hands dirty with a simple example. In this era, public data is plentiful and available for the taking. From public zoning data to subway times, many cities offer public data via easy-to-consume APIs. In this article, we take the BART (Bay Area Rapid Transit) API as our basis—an API that provides a wide array of metrics, statistics, and schedules for the Bay Area's largest rail system—to create real-time updates enabled transportation schedule application which can be a big boost for public transportation apps.

How to Create a Transportation App: Programming Scope
-----------------------------------------------------

![](https://www.pubnub.com/cdn/3prze68gbwl1/asset-17suaysk1qa1hy3/51833020ec055e2ee9ecf7de3add5e60/times.png)

This article will guide you on how to leverage the BART API to build a real-time public transportation schedule application, presenting real-time updates and service alerts to its users, much like Google Maps, Moovit, and Uber. It aims to improve user experience by providing valuable information from departure times to possible disruptions in service. You'll learn how to fetch station locations (like a metro station or a bus stop) and convert them into geohashes. After collecting the information, you'll pinpoint the user's location in San Francisco (or spoof it in our case), then you'll match the user’s location with nearby stations, which will require more API calls for fetching relevant data.

Once you've obtained the estimated departure times, you'll display the times on a map infobox. The entire process is simplified in a step-by-step tutorial, accompanied by code snippets and explanations.

Getting Started with Your Transportation Schedule App
-----------------------------------------------------

To create your real-time transit app, the setup is similar to our [previous tutorial on JavaScript geohashing](https://pubnub.com/blog/calculating-geolocation-proximity-w-javascript-geohashing/). With the help of effective trip planning algorithms and utilizing the power of real-time data, you can create a unique user-friendly mobile app for iOS, Android, and other mobile devices that can effectively manage real-time updates relevant to public transportation.

Firstly, you'll need "node" and "npm" for the ETA module of your app. If you're unfamiliar with these terms, then take a look at [PubNub's comprehensive introduction to Node.js](https://pubnub.com/blog/node-js-supercharged-by-pubnub/).

The node packages used are:

-   [Browserify](http://browserify.org/) to use node packages in the browser.
    
-   [ngeohash](https://github.com/sunng87/node-geohash) to encode latitude and longitude into a string.
    
-   [request](https://github.com/request/request) for HTTP requests outside of the browser.
    
-   [xml2js](https://github.com/Leonidas-from-XIV/node-xml2js) to convert XML returns into JSONs.
    

These packages provide the necessary functionalities to call APIs, handle data, and perform tasks required for our application. If you look at the example code, you'll notice that these packages are missing. You simply need to navigate to the project base folder and type \`npm install\` in the command line. This will install the packages based on the requirements in \`package.json\`.

In the following sections, we will dive into the specifics of working with geolocation data, processing push notifications efficiently, displaying vehicle locations effectively, and creating a great user experience with your application. Stay tuned!

User Hash and Map Location for Your Transit Schedule Application
----------------------------------------------------------------

HTML5 Geolocation API is a handy tool that enables access to geographical location (longitude and latitude) based on a device IP, RFID, WIFI, Bluetooth MAC address, GPS, or user input. Here's how to use it to get the user's location to provide real-time tracking, similar to how transportation apps like Uber or Google Maps do:

```js
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
  //...
```

This code checks if the browser supports geolocation, then gets the user's current position. For testing purposes in this tutorial, we will set our coordinates to signify a location in the Bay area.

```js
    that.lat = 37.6;
    that.lng = -122.4;
    var lat = that.lat;
    var lng = that.lng;
```

Our app will require the station data to display on the map. We import these data from \`app.js\`.

```js
    var app = require("./app.js");
```

Next, we set local variables for our data:

```js
    var json_data, hash_table, hash_matches, destinations;
    …
    json_data_formatted = app.formatted_json;
    hash_table = app.hash_table;
    hash_matches = app.hash_matches;
    destinations = app.destinations;
```

Next, we'll integrate the PubNub and Google Maps:

```js
    pubs();
    google.maps.event.addDomListener(window, 'load', initialize());
```

The \`pubs()\` function is called from line 130 and initializes PubNub with your unique publish and subscribe keys. If you don't have PubNub keys, you can [sign up for a PubNub account](https://admin.pubnub.com/signup/) to get them.

```js
function pubs() {
     var pubnub = new PubNub({
       publishKey: "publish_key",
       subscribeKey: "subscribe_key",
       userId: "UUID"
   });
},
```

The logic for the Google Map is borrowed from [one of the previous articles](https://pubnub.com/blog/calculating-geolocation-proximity-w-javascript-geohashing/). The PubNub connection listens for coordinate messages sent to the channel "mymaps", then moves the user's marker based on the received information.

Google Maps' \`initialize()\` function is called, adding properties to the map. Importantly, it adds a marker for each \`hash\_match\`.

```js
    var business_marker = new google.maps.Marker({position: {lat: match_lat, lng: match_lng}, map: map});
    business_marker.setMap(map);
```

Then, an event listener is added for info windows.

```js
    google.maps.event.addListener(business_marker, 'mouseover', function() {
      infowindow.open(map,business_marker);
    });
    google.maps.event.addListener(business_marker, 'mouseout', function() {
      infowindow.close(map,business_marker);
```

Searching for Train Schedules for Your Transit App
--------------------------------------------------

Once you've taken care of displaying items on the map, the next step involves adding information about departure times. This is achieved by going back to \`app.js\` and populating the hash\_matches with data for each of the matches.

In this example, we're only saving data for the Millbrae station. We're making an Ajax call on the Millbrae data:

```js
    $.ajax({
      type: "GET",
      url: "data/MLBR.json",
      dataType: "json",
      success: function(file) {
        main_two(file);
      }
    });
```

This function, \`main\_two\`, formats the data and prepares it for interaction with Google Maps.

### Displaying Schedules for Your Transit Schedule

Now, revisit \`gmap.js\`. Here, loop through the various destination names. In this case, \`Millbrae\` has been hard-coded, but ideally, you would use a variable to match abbreviations between \`hash\_matches\` and \`destinations\`, displaying the relevant times.

```js
    var times = destination.times;
    dest_string = dest_string + "<p><i>" + destination.abbreviation + ":" + "</i><p>";
    times.forEach(function(time) {
      dest_string = dest_string + " " + time;
    });
```

Next, specify the info window:

```js
    var infowindow = new google.maps.InfoWindow({
      content: "<b>" + BusinessName + "</b>" +
    "<p>" + dest_string + "</p></p></p>"
    });
```

That's it! You have successfully displayed items on a map and added information about departure times. If you're interested in more about real-time mapping and geolocation using APIs such as MapBox, MapKit, and Google Maps, check out our [other tutorials](https://pubnub.com/blog/category/tutorials/).

Experience PubNub
-----------------

How about getting a feel of PubNub? Check out our [Live Tour](https://www.pubnub.com/tour/introduction/) to understand the essential concepts behind every PubNub-powered app in less than 5 minutes. You can [sign up](https://admin.pubnub.com/signup/) for a PubNub account and [get started](https://www.pubnub.com/docs) with your project. Working with PubNub can bring your app to life with real-time updates, push notifications, and user-friendly interface, opening a new realm of possibilities for transportation apps.

Whether you're an Apple or Android user, whether you commute by bus, subway, or bikeshare, having a real-time transit app handy is crucial. By leveraging PubNub's powerful APIs and the easily accessible GTFS data from transport agencies, you can contribute to transforming public transportation, creating an efficient, user-friendly digital solution for commuters, transportation services, and agencies alike. Just think - no more traffic jams, no more uncertainty about arrival times, just seamless public transit with real-time updates. So why wait? Let's hop on to this journey of transforming the transportation system with PubNub.

#### Contents

[How to Create a Transportation App: Programming Scope](#h-0)[Getting Started with Your Transportation Schedule App](#h-1)[User Hash and Map Location for Your Transit Schedule Application](#h-2)[Searching for Train Schedules for Your Transit App](#h-3)[Displaying Schedules for Your Transit Schedule](#h-4)[Experience PubNub](#h-5)

How can PubNub help you?
========================

This article was originally published on [PubNub.com](https://www.pubnub.com/blog/how-to-build-a-realtime-public-transit-schedule-app/)

Our platform helps developers build, deliver, and manage real-time interactivity for web apps, mobile apps, and IoT devices.

The foundation of our platform is the industry's largest and most scalable real-time edge messaging network. With over 15 points-of-presence worldwide supporting 800 million monthly active users, and 99.999% reliability, you'll never have to worry about outages, concurrency limits, or any latency issues caused by traffic spikes.

Experience PubNub
-----------------

Check out [Live Tour](https://www.pubnub.com/tour/introduction/) to understand the essential concepts behind every PubNub-powered app in less than 5 minutes

Get Setup
---------

Sign up for a [PubNub account](https://admin.pubnub.com/signup/) for immediate access to PubNub keys for free

Get Started
-----------

The [PubNub docs](https://www.pubnub.com/docs) will get you up and running, regardless of your use case or [SDK](https://www.pubnub.com/docs)