Want to track your pizza’s progress in real-time? Now you can with Pusher’s real-time APIs and Google Maps. In this tutorial, the guys over at the Pusher blog show you how to build your own food delivery-tracking web app hosted on Heroku.
Step 0: setting up your app
First off, create an index.html with the following code featuring a meta tag to ensure the whole thing looks good on mobile.
Then get an API key for Google Maps and add the JS files to your html with your API key.
Step 1: capture device location
Then you want to capture the user’s location on loading the page with the geolocation API.
Step 2: capture the deliverer name
Step 3: set up tracking logic and send events on location change
To track the user and deliverer locations, you need to use Pusher’s real-time capabilities. The idea is to trigger events whenever thre’s a change in the user’s or his location, which we’ll listen out for with Pusher.
First things first, sign up for Pusher or login if you have an account. Then create an app giving an app name and choose a cluster in the create app screen.
Once the app’s created, add Pusher’s JS library to your index.html. Connect to your app by calling the Pusher constructor with your app key.
Now you want to use Pusher channels to let the deliverer track the user location securely. To do this, name the channel after the username chosen by the user. The deliverer can then subscribe to this channel and listen for location change events created by the user.
To create a private channel, you’ll need to create an auth server. Then enable client events in the Settings tab on Pusher’s dashboard.
Next, we’ll create a new channel on app startup with the code below. This will send client events to the deliverer every time the user location changes. You’ll save the last location in a JS object named myLastKnownLocation. In cases where the user isn’t moving, we’ll add a setInterval to keep sending the last location over the channel.
Step 4: subscribe to the deliverer location channels
Lastly, you’ll want to track the deliverer’s movements. To do this, add a username button for the deliverer along with an event listener. For this event listener add a function that subscribes to the Pusher channel of the deliverer and listens out for all events on that channel. This function should save the user’s location with each new event.
Then create a new function to plot this new location on the map. In this way, you can see the pointer moving across the map as the deliverer gets closer to you.
You can add multiple buttons for each of your deliverers so you can track many different deliverers in real-time by adding new text-boxes for other deliverers. When you click the button associated with any new deliverer, the screen will center the map with his last known location.